通常使用stream流转为map的方法为Collectors.toMap
具体示例如下:
List list = new ArrayList();
list.add(new Student("0001", "学生甲"));
list.add(new Student("0002", "学生乙"));
list.add(new Student("0003", "学生丙"))
//转为map
Map map = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(map);
输出结果为:
0001=学生甲,0002=学生乙,003=学生丙
上述为一个key对应一个value,以下为一个key对应多个value情况
List list = new ArrayList();
list.add(new Student("0001", "学生甲"));
list.add(new Student("0002", "学生乙"));
list.add(new Student("0001", "学生丙"))
直接转map会产生异常,转换map时,key重复
转为map有三种方法:
1.后面的value覆盖以前的value值
Map map = list.stream().collect(Collectors.toMap(Student::getId, Student::getName,(key1 , key2)-> key2 ));
System.out.println(map);
输出结果为:{0001=学生丙,0002=学生乙}
2.同一key的value值进行拼接
Map map = list.stream().collect(Collectors.toMap(Student::getId, Student::getName,(key1 , key2)-> key1+","+key2 ));
System.out.println(map);
输出结果为:{0001=学生甲,学生丙,0002=学生乙}
3.同一key的value转为list
Map> map = list.stream().collect(Collectors.toMap(Student::getId,
p -> {
List getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List value1, List value2) -> {
value1.addAll(value2);
return value1;
}
));
System.out.println(map);
输出结果为:{0001=[学生甲,学生丙],0002=[学生乙]}