List转换为Map
1.key和value都是对象中的某个属性值。
Map<String, String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId, User::getName));
Map<String, User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId, User -> User));
3.key是对象中的某个属性值,value是对象本身(使用Function.identity()的简洁写法)。
Map<String, User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
4.key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。
如果不正确指定Collectors.toMap方法的第三个参数(key冲突处理函数),那么在key重复的情况下该方法会报出【Duplicate Key】的错误导致Stream流异常终止,使用时要格外注意这一点。
Map<String, User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (oldValue, newValue) -> newValue));
用groupingBy 或者 partitioningBy进行分组
根据一个字段或者属性分组也可以直接用groupingBy方法,很方便。
public class Student{ //年级 private String grade; //班级 private String classNumber; //姓名 private String name; //年龄 private int age; //地址 private String address; //数学成绩 private int mathScores; //语文成绩 private int chainessScores; }
Map<String, List<Student>> collect = students.stream().collect(Collectors.groupingBy(Student::getClassNumber));
System.out.println(JSON.toJSONString(collect));