Stream 将List<对象>转换为Map
2020-12-03  本文已影响0人  程序员小白成长记
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}]

上一篇 下一篇

猜你喜欢

热点阅读