티스토리 뷰
자바에서 흔히 정렬을 할때, 정렬 기준을 임의로 바꿔야 할 때가 자주 있다.
이때 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;
});
'개발 > Java' 카테고리의 다른 글
[Java] - Garbage Collection(GC) Eden 의미 (2) | 2022.09.21 |
---|---|
[Java] - Gmail SMTP를 이용한 메일보내기 (0) | 2021.11.23 |