Comparator比较器

一、代码解析

default Comparator<T> thenComparing(Comparator<? super T> other) {
    Objects.requireNonNull(other);
    return (Comparator<T> & Serializable) (c1, c2) -> {
        int res = compare(c1, c2);
        return (res != 0) ? res : other.compare(c1, c2);
    };
}

		List<Employee> employeeList = Arrays.asList(
		new Employee("赵1", 12,85),
		new Employee("赵2", 13,102),
		new Employee("赵3", 11,90),
		new Employee("赵4", 13,90)
		//new Employee("赵4", 15),
		//new Employee("赵5", 10),
		//new Employee("赵5", 10)
    );
	
	// 自定义排序
    Comparator<Integer> keyComparator = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return 0;
        }
    };
    List<Employee> collect = employeeList.stream()
            .sorted(Comparator.comparing(Employee::getAge,Comparator.reverseOrder()) // 使用ReverseComparator的compare(x,y)进行比较
            .thenComparing(Employee::getSroce, keyComparator)) // 优先比较x与y的Age字段是否相等,若相等则,调用keyComparator自定义比较器,比较sroce字段
            .collect(Collectors.toList());
    System.out.println("---collect---"+JSONObject.toJSON(collect));
posted @ 2022-11-04 17:07  jock_javaEE  阅读(84)  评论(0编辑  收藏  举报