欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

流将列表转换为地图>。

最编程 2024-06-29 07:22:46
...
public static void main(String[] args) {
    List<Student> stu = new ArrayList<>();
    Student s1 = new Student();
    s1.setId(1);
    s1.setName("zs");

    Student s2 = new Student();
    s2.setId(1);
    s2.setName("ls");

    Student s3 = new Student();
    s3.setId(3);
    s3.setName("ww");

    stu.add(s1);
    stu.add(s2);
    stu.add(s3);
    stu.stream().forEach(e -> System.out.println(e.getId() + " " + e.getName()));
    // 关键语句
    Map<Integer, List<Student>> map = stu.stream().collect(Collectors.groupingBy(e -> e.getId()));
    System.out.println(map);
}

结果
1: [{1,zs},{1,ls}]
3: [{3,ww}]