关于java8:java8之flatMap应用

31次阅读

共计 947 个字符,预计需要花费 3 分钟才能阅读完成。

    @Test
    public void testFlatMap() {Teacher yuwen1 = Teacher.builder().teacherName("飞老师").level(1).build();
        Teacher yuwen2 = Teacher.builder().teacherName("木老师").level(2).build();
        Teacher shuxue1 = Teacher.builder().teacherName("算老师").level(3).build();

        List<Teacher> teacherList = new ArrayList<>(Arrays.asList(yuwen1, yuwen2));
        List<Teacher> teacher2List = new ArrayList<>(Arrays.asList(shuxue1));
        Student zhangsan = Student.builder().name("张三").gender("男").teacherList(teacherList).build();
        Student lisi = Student.builder().name("李四").gender("男").teacherList(teacherList).build();
        Student wangwu = Student.builder().name("王五").gender("女").teacherList(teacher2List).build();

        List<Student> students = new ArrayList<>(Arrays.asList(zhangsan, lisi, wangwu));

        Set<Teacher> allStudentsTeachers = students.stream().flatMap(e -> e.getTeacherList().stream()).collect(Collectors.toSet());
        allStudentsTeachers.stream().forEach(System.out::println);
    }

留神是: e -> e.getTeacherList().stream()
留神 外部 list 还要被 ” 化骨绵掌 ” 击为 stream!!!

正文完
 0