Java8 Stream sorted

Java8 Stream sorted

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

    public static void main(String[] args) {
     	List<String> strings = Arrays.asList("555", "333", "444", "111", "222", "666", null);
     	List<Integer> integers = Arrays.asList(555, 333, 444, 111, 222, 666, null);
     	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());
        
        //1 sorte()d对list<String>进行自然排序
        strings.stream()
                .map(s -> Optional.ofNullable(s).orElseGet(String::new))
                .sorted()
                .forEach(System.out::println);
        System.out.println();
        //2 sorte()d对list<int>进行自然排序
        integers.stream()
                .map(s -> Optional.ofNullable(s).orElse(0))
                .sorted()
                .forEach(System.out::println);
        System.out.println();
        //3 sorte()d对list<Student>进行自然排序
        classOneStudents.stream()
                .map(s -> Optional.ofNullable(s).orElseGet(Student::new))
                .sorted()
                .forEach(System.out::println);
        //4 sorte()d对list<Student>进行自定义排序
        System.out.println();
        classOneStudents.stream()
                .sorted((student1, student2) -> student1.getScore() > student2.getScore() ? 1 : -1)
                .forEach(System.out::println);
        System.out.println();
        //5 按照入学顺序enrolOrders进行展示
        //5.1 生成一个Map<studentName,Student>
        Map<String, Student> collect = classOneStudents.stream()
                .collect(Collectors.toMap(student -> student.getName(), Function.identity(),
                        (student1, student2) -> student2));
        //5.2 按照enrolOrders中的name顺序去Map<studentName,Student>中拿Student,并生成新的List
        enrolOrders.stream()
                .map(enrolOrder->collect.get(enrolOrder))
                .forEach(System.out::println);
    }
    原文作者:Weison Wei
    原文地址: https://blog.csdn.net/weixx3/article/details/82892087
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞