乐趣区

关于java8:java8之flatMap应用

    @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!!!

退出移动版