java8中stream 排序去重

参考: https://blog.csdn.net/weixin_30388677/article/details/97833849


import lombok.Data;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @date 2021/6/15/19:17
 */
public class ListStream {
    
    


    @Test
    public void demo() {
    
    
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(3);
        list.add(5);
        list.add(1);
        list.add(0);
        System.out.println(list);
        // 升序
        List<Integer> list1 = list.stream().sorted().collect(Collectors.toList());
        System.out.println(list1);
        //降序
        List<Integer> list2 = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        System.out.println(list2);
        //去重
        List<Integer> list3 = list.stream().distinct().collect(Collectors.toList());
        System.out.println(list3);
    }

    @Data
    class Student {
    
    

        public Student(String name, Integer age) {
    
    
            this.age = age;
            this.name = name;
        }

        private String name;
        private Integer age;
    }


//对象根据属性 排序去重
    @Test
    public void demo2() {
    
    
        List<Student> list = new ArrayList<>();
        list.add(new Student("张三", 3));
        list.add(new Student("王二", 2));
        list.add(new Student("麻子", 1));
        list.add(new Student("李四", 4));
        list.add(new Student("李明", 3));
        System.out.println(list);

        //升序
        List<Student> orderList = list.stream()
                .sorted(Comparator.comparing(Student::getAge))
                .collect(Collectors.toList());
        System.out.println(orderList);
        //多字段排序 https://blog.csdn.net/weixin_30388677/article/details/97833849

        //降序
        List<Student> collect = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
        System.out.println(collect);
        
       //降序
       // Collections.reverse(orderList);
       // System.out.println(orderList);


        //去重
        ArrayList<Student> studentArrayList  = list.stream().
                collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getAge))), ArrayList::new));
        System.out.println(studentArrayList);

    }


}


Guess you like

Origin blog.csdn.net/xy3233/article/details/117931652