Collectors.toMap用法
List<Student> studentList = new ArrayList<>();
studentList.add(new Student(1, "小福贵"));
studentList.add(new Student(2, "图图"));
studentList.add(new Student(3, "喜羊羊"));
studentList.add(new Student(3, "懒羊羊"));
Map<Integer, Student> map = studentList.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (a, b)-> b));
System.out.println(JSON.toJSONString(map));
运行结果:
{
"1": {
"id": 1,
"name": "小福贵"
},
"2": {
"id": 2,
"name": "图图"
},
"3": {
"id": 3,
"name": "懒羊羊"
}
}
- 第一个参数:用来生成key的值
- 第二个参数:用来生成value的值
v->v
表示将原来的对象作为value值
Function.identity()
等价于v->v
- 第三个参数:
(a, b)-> b
,key冲突时,取b所对应的value值(key冲突,不写该参数会报错)
Collectors.groupingBy用法
Map<Integer, List<Student>> groupingBy = studentList.stream().collect(Collectors.groupingBy(Student::getId));
运行结果:
{
"1": [
{
"id": 1,
"name": "小福贵"
}
],
"2": [
{
"id": 2,
"name": "图图"
}
],
"3": [
{
"id": 3,
"name": "喜羊羊"
},
{
"id": 3,
"name": "懒羊羊"
}
]
}
与toMap
区别:
toMap
是1:1的k-v结构,groupingBy
是1:n的k-v结构