没描述,直接看结果吧。
package com.anchnet.sync;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author H.Yang
* @date 2021/11/19
*/
@Slf4j
public class AppDemo {
public static void main(String[] args) {
List<Student> list = new LinkedList<>();
list.add(new Student("A1", "男", 10001));
list.add(new Student("A2", "女", 10002));
list.add(new Student("A3", "男", 10002));
list.add(new Student("A4", "女", 10001));
list.add(new Student("A5", "男", 10003));
// 核心代码
Map<Integer, List<Student>> map = list.stream().collect(Collectors.groupingBy(item -> item.getTeacherId(), Collectors.mapping(item -> item, Collectors.toList())));
System.out.println(JSONUtil.toJsonStr(map));
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Student {
private String name;
private String sex;
private Integer teacherId;
}
结果
{
"10002": [
{
"sex": "女",
"teacherId": 10002,
"name": "A2"
},
{
"sex": "男",
"teacherId": 10002,
"name": "A3"
}
],
"10001": [
{
"sex": "男",
"teacherId": 10001,
"name": "A1"
},
{
"sex": "女",
"teacherId": 10001,
"name": "A4"
}
],
"10003": [
{
"sex": "男",
"teacherId": 10003,
"name": "A5"
}
]
}