• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

Java8 Stream 操作总结

java8 来源:Weison Wei 1次浏览

Java8 Stream 操作总结

1 map与方法引用

map()要么改变了element的值,要么改变了element中某属性的值
只要参数返回一致就可方法引用,被引用方法根据其方法类型有几种不用的引用姿势

public class Main { 
    public void mapString() { 
        Stream<String> arrayStream = Arrays.asList("555", "333", "444", "111", "222", "666").stream();
        arrayStream.map(this::mapString);
        arrayStream.map((s) -> mapString(s));
        arrayStream.forEach(System.out::println);
    }

    private String mapString(String str) { 
        return str + ",";
    }
}

2 flatmap展开多个Collection

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);
}

3 reduce字符串、数值操作

reduce字符串、数值操作

	String str3 = Stream.of("A", "B", "C", "D")
                  		.reduce("", (s1, s2) -> s1 + "1" + s2 + "2", (s1, s2) -> s1 + "*" + s2);
	System.out.println("拼接字符串str3:" + str3); //拼接字符串str3:1A21B21C21D2

	int sumValue1 = Stream.of(1, 2, 3, 4)
                .reduce(10, Integer::sum);
    int sumValue2 = Stream.of(1, 2, 3, 4)
                .reduce(10, (v1, v2) -> v1 + v2);
    System.out.println("求和有起始值:" + sumValue1);//求和有起始值:20
    System.out.println("求和有起始值:" + sumValue2);//求和有起始值:20

4 stream中的排序

sorted()对stream进行自然顺序排序,或传入Comparator实现自定义的排序

    public static void main(String[] args) { 
     	List<Student> classOneStudents = new ArrayList<>();
	 	List<String> enrolOrders = Arrays.asList("Luis", "Weison", "Jack", "Evan");
	 	classOneStudents.add(Student.builder().age(19).name("Evan").score(80).build());
     	classOneStudents.add(Student.builder().age(18).name("Weison").score(90).build());
     	classOneStudents.add(Student.builder().age(21).name("Luis").score(60).build());
     	classOneStudents.add(Student.builder().age(20).name("Jack").score(70).build());
        
        // 按照入学顺序enrolOrders进行展示
        //1 生成一个Map<studentName,Student>
        Map<String, Student> nameStudentMap= classOneStudents.stream()
                .collect(Collectors.toMap(student -> student.getName(), Function.identity(),
                        (student1, student2) -> student2));
        //2 按照enrolOrders中的name顺序去Map<studentName,Student>中拿Student,并生成新的List
        enrolOrders.stream()
                .map(enrolOrder->nameStudentMap.get(enrolOrder))
                .forEach(System.out::println);
    }

5 collect 分组操作

toMap()时,最好加上mergeFucntion,以免java.lang.IllegalStateException: Duplicate key

   public static void main(String[] args) { 
        List<String> strings = Arrays.asList("555", "333", "444", "111", "222", "666", "555", null);
        List<Integer> integers = Arrays.asList(555, 333, 444, 111, 222, 666);
        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(5).name("Weison").sex("男").score(90).citationCount(1).build());
        classOneStudents.add(Student.builder().age(6).name("Evan").sex("女").score(80).citationCount(2).build());
        classOneStudents.add(Student.builder().age(7).name("Jack").sex("男").score(70).citationCount(2).build());
        classOneStudents.add(Student.builder().age(8).name("Luis").sex("女").score(60).citationCount(4).build());

        classTwoStudents.add(Student.builder().age(9).name("Elen").sex("女").score(80).citationCount(2).build());
        classTwoStudents.add(Student.builder().age(10).name("Obam").sex("男").score(70).citationCount(5).build());
        classTwoStudents.add(Student.builder().age(11).name("Bush").sex("女").score(60).citationCount(3).build());

        classThreeStudents.add(Student.builder().age(12).name("Jackson").sex("男").score(70).citationCount(1).build());
        classThreeStudents.add(Student.builder().age(13).name("Linn").sex("女").score(60).citationCount(1).build());
        students.add(classOneStudents);
        students.add(classTwoStudents);
        students.add(classThreeStudents);
        // toMap
        // 不添加mergeFucntion 会报 java.lang.IllegalStateException: Duplicate key 5551
        Map<String, String> stringsMap =
                strings.stream()
                        .filter(element -> null != element)
                        .collect(Collectors.toMap(stringsValue -> stringsValue,
                                stringsValue -> stringsValue + "1",
                                (stringsValue1, stringsValue2) -> stringsValue2));
        System.out.println("stringsMap-->" + stringsMap);

        Map<String, Student> studentMap =
                classOneStudents.stream()
                        .collect(Collectors.toMap(student -> student.getName(),
                                Function.identity(),
                                (student1, student2) -> student2));
        System.out.println("studentMap-->" + studentMap);

        // groupingBy 分组并求每组的数量
        Map<String, Long> stringLongMap = students.stream()
                .flatMap(student -> student.stream())
                .collect(Collectors.groupingBy(Student::getSex, Collectors.counting()));
        System.out.println("stringLongMap--->" + stringLongMap); // {女=5, 男=4}

    }

6 Java8 练习代码

代码链接


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)