Set常用方法

去重排序

public class Demos {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>();
        students.add(new Student("张三","男",20));
        students.add(new Student("张三","男",20));
        students.add(new Student("李四","男",11));
        students.add(new Student("李四","男",66));
        students.add(new Student("王五","女",45));
        students.add(new Student("小六","女",21));
        System.out.println(students);
 
        System.out.println("********************写法一********************");
        Set<Student> sortSet1 = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.compareTo(o1);
            }
        });
        sortSet1.addAll(students);
        System.out.println(sortSet1.toString());
 
        System.out.println("********************写法二********************");
        Set<Student> sortSet2 = new TreeSet<Student>(((o1, o2) ->Integer.compare(o2.getAge(), o1.getAge())));
        sortSet2.addAll(students);
        System.out.println(sortSet2.toString());
 
        System.out.println("********************写法三********************");
        Set<Student> sortSet3 = new TreeSet<Student>(Comparator.reverseOrder());
        sortSet3.addAll(students);
        System.out.println(sortSet3.toString());
 
        System.out.println("********************写法四********************");
        //这里后续用有序的list处理即可,因为流中进行了倒序处理,收集成set后会重排
        List<Student> collect = students.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        System.out.println(collect);
    }
}