본문 바로가기
  • Where there is a will there is a way.
개발/java

java 복잡한 Comparator 예제

by 소확행개발자 2019. 12. 19.

comparator 를 사용할때 가끔은 복잡한 정렬이 필요할 때가 있다..

항상 쓸때마다 헷갈림으로 남겨놓습니다..

 

@Test
    public void test() {


        List<Integer> test = Lists.newArrayList(9, 10, 5, 4, 6, 7, 7, 8, 8, 9);

        Comparator<Integer> sortList = Comparator.comparingInt(o -> o);

        Collections.sort(test, sortList);

        System.out.println(test);
    }


    @Test
    public void test_복잡한정렬조건() {

        List<AreaSortTest> areaSortTests = new ArrayList<>();

        areaSortTests.add(new AreaSortTest(0, 10, LocalDateTime.now()));
        areaSortTests.add(new AreaSortTest(0, 10, LocalDateTime.now().minusDays(1)));
        areaSortTests.add(new AreaSortTest(0, 7, null));
        areaSortTests.add(new AreaSortTest(1, 0, null));
        areaSortTests.add(new AreaSortTest(2, 0, null));
        areaSortTests.add(new AreaSortTest(3, 0, null));

        Comparator<AreaSortTest> areaSortTestComparator = (o1, o2) -> {

            if(o1.getRecommendCnt() == 0 && o2.getRecommendCnt() == 0) {

                if(o2.getBuyCnt().equals(o1.getBuyCnt())) {
                    return o1.getModDate().isAfter(o2.getModDate()) ? -1 : 1;
                } else {
                    return (o2.getBuyCnt()) - (o1.getBuyCnt());
                }
            } else if(o1.getRecommendCnt() != 0 && o2.getRecommendCnt() != 0) {
                return o1.getRecommendCnt() - o2.getRecommendCnt();
            } else {
                return o2.getRecommendCnt() - o1.getRecommendCnt();
            }

        };

        Collections.sort(areaSortTests, areaSortTestComparator);

        System.out.println(areaSortTests);


    }

'개발 > java' 카테고리의 다른 글

heap 메모리와 Garbage Collector  (1) 2020.03.21
spring 에서 pageable custom 구현  (0) 2019.12.19
템플릿 메소드 패턴  (2) 2019.07.04
어댑터 패턴  (0) 2019.07.01
커맨드 패턴  (0) 2019.06.30

댓글