Java8 Stream flatmap

Java8 Stream flatmap

flatMap用于把Stream中的层级结构扁平化并返回Stream,入参出参都是Stream

    public static void main(String[] args) {
    
        List<Student> classOneStudents = new ArrayList<>();
    	List<Student> classTwoStudents = new ArrayList<>();
    	List<Student> classThreeStudents = new ArrayList<>();
    	List<List<Student>> students = new ArrayList<>();
    	
        classOneStudents.add(Student.builder().age(18).name("Weison").score(90).build());
        classOneStudents.add(Student.builder().age(19).name("Evan").score(80).build());
        classOneStudents.add(Student.builder().age(20).name("Jack").score(70).build());
        classOneStudents.add(Student.builder().age(21).name("Luis").score(60).build());

        classTwoStudents.add(Student.builder().age(19).name("Elen").score(80).build());
        classTwoStudents.add(Student.builder().age(20).name("Obam").score(70).build());
        classTwoStudents.add(Student.builder().age(21).name("Bush").score(60).build());

        classThreeStudents.add(Student.builder().age(20).name("Jackson").score(70).build());
        classThreeStudents.add(Student.builder().age(21).name("Linn").score(60).build());
        students.add(classOneStudents);
        students.add(classTwoStudents);
        students.add(classThreeStudents);
        
        //5 flatMap 把Stream中的层级结构扁平化并返回Stream
        List<Student> studentList = students
                .stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
                
        //展开多个List合并到一个新list
        studentList
                .stream()
                .forEach(System.out::println);
}
    原文作者:Weison Wei
    原文地址: https://blog.csdn.net/weixx3/article/details/82834052
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞