public class LambdaDemo {
private List<Id> ids;
@Data
@NoArgsConstructor
@AllArgsConstructor
static class Student{
private String name;
private String city;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
static class Id{
private Integer id;
}
/**
* 遍历List和Map
*/
public static void listAndMapForEach() {
List<String> list = new ArrayList<>();
list.add("张三");
list.add("李四");
list.add("王五");
list.forEach(System.out::println);
Map<String, String> map = new HashMap<>();
map.put("name", "zjc");
map.put("city", "广州");
map.forEach((k, v) -> System.out.println(k + " : " + v));
}
/**
* List 转为 Map
*/
public static void listToMap(){
Student t1 = new Student("zjc", "GZ");
Student t2 = new Student("lisi", "BJ");
Student t3 = new Student("zjc", "SZ");
List<Student> studentList = new ArrayList<>();
studentList.add(t1);
studentList.add(t2);
studentList.add(t3);
// 1. 简单的合并, (k1,k2) -> k1) 解决k重复,导致报错问题
/*Map<String, Student> studentMap = studentList.stream().collect(
Collectors.toMap(Student::getName, Function.identity(),(k1,k2) -> k1));
studentMap.forEach((k,v) -> System.out.println(k+" : "+v));*/
// 2. 同一个主键 合并到集合中
Map<String, List<Student>> studentMap = studentList.stream().collect(Collectors.groupingBy(Student::getName));
studentMap.forEach((k,v) -> System.out.println(k+" : "+v));
}
public static void setToObjectList(){
Set<Integer> idSet = new HashSet<>();
idSet.add(1);
idSet.add(2);
List<Id> ids = idSet.stream().map(Id::new)
.collect(Collectors.toList());
ids.forEach(System.out::println);
}
public static void main(String[] args) {
// listAndMapForEach();
// listToMap();
setToObjectList();
}
}
Java 8 Lambda 表达式学习
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。