Java 集合多字段排序

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class TimeBetweenRecent {
        private Long startTime;
        private Long endTime;

        public TimeBetweenRecent(Long startTime, Long endTime) {
            this.startTime = startTime;
            this.endTime = endTime;
        }
    }

    @Test
    public void test() {
        List recents = new ArrayList<>();
        recents.add(new TimeBetweenRecent(1L, 5L));
        recents.add(new TimeBetweenRecent(1L, 4L));
        recents.add(new TimeBetweenRecent(2L, 6L));
        recents.add(new TimeBetweenRecent(2L, 7L));
        //startTime 升序
        Comparator c1 = Comparator.comparingLong(
                TimeBetweenRecent::getStartTime);
        //endTime 降序
        Comparator c2 = Comparator.comparingLong(
                TimeBetweenRecent::getEndTime).reversed();

        recents.sort(c1.thenComparing(c2));
        System.out.println(recents);
    }

你可能感兴趣的:(Java 集合多字段排序)