개발/Java

[Java] - Comparator

dongdev 2021. 10. 21. 23:33

자바에서 흔히 정렬을 할때, 정렬 기준을 임의로 바꿔야 할 때가 자주 있다.

이때 Comparator 인터페이스를 사용하면 쉽게 바꿔줄 수 있다.

코드로 한번 보자.

 

ex)

class Location {
    int x;
    int y;
}
List<Location> locationList = new ArrayList<>();
locationList.add(new Location());

Collections.sort(locationList, new Comparator<Location>() {
    @Override
    public int compare(Location o1, Location o2) {
        if (o1.x == o2.x) { //x가 같을 때, y에 대해선 내림차순 정렬
            return o2.y - o1.y;
        } else
            return o1.x - o2.x; //x에 대해선 오름차순 정렬
    }
});

 

람다식으로 변경

Collections.sort(locationList, (o1, o2) -> {
    if (o1.x == o2.x) {
        return o2.y - o1.y;
    } else
        return o1.x - o2.x;
});