import java.util.Arrays;
int[] arr = {5, 4, 6, 1, 3, 2};
Arrays.sort(arr);
int[][] arr = new int[][]{{1,2}, {2,4}, {2,1}, {3,5}, {3,2}, {4,4}}
// 첫 번째 숫자 기준 오름차순
Arrays.sort(arr, (o1, o2) -> {
return o1[0] - o2[0];
});
// 첫 번째 숫자로 먼저 정렬 후, 두 붠째 숫자로 정렬
Arrays.sort(arr, (o1, o2) -> {
if(o1[0] == o2[0]){
return o1[1] - o2[1];
}else{
return o1[0] - o2[0];
}
});
Arrays.sort(arr, (o1, o2) -> o1[1].compareTo(o2[1]));
두 인터페이스는 객체를 비교할 수 있도록 만듭니다. 기본 자료형은 부등호로 쉽게 비교할 수 있습니다. 그러나, 객체는 사용자가 정해준 기준으로 비교할 수 있습니다. 예를 들어, 학생 a와 학생 b가 있는데, 두 학생을 무엇을 두고 비교할 것인가? 기준이 나이일 수도 있고, 학급이 될수도 있다. 즉, 어떠한 기분을 두고 비교하기 위해서 Comparable과 Comparator가 필요합니다.
public class ClassName implements Comparator<Type> {
// 필수 구현 부분
@Override
public int compareTo(Type o) {
// 비교 구현
}
}
예시 : 학생의 나이를 기준으로 비교
class Student implements Comparable<Student> {
int age;
int classNumber;
Student(int age, int classNumber) {
this.age = age;
this.classNumber = classNumber;
}
@Override
public int compareTo(Student o) {
// 자기자신의 age가 o의 age보다 크다면 양수
if(this.age > o.age) {
return 1;
}
// 자기 자신의 age와 o의 age가 같다면 0
else if(this.age == o.age) {
return 0;
}
// 자기 자신의 age가 o의 age보다 작다면 음수
else {
return -1;
}
}
}
예를들어) 자기 자신은 7이입니다.
int[][] arr = new int[][]{{1,2}, {2,4}, {2,1}, {3,5}, {3,2}, {4,4}}
// 1. Comparator 익명 클래스 구현
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// 정수형 타입의 정렬이다.
// 만약 실수형 타입이라면 int compare(Double[] o1, Double[] o2)
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0]; // 첫 번째 숫자 기준 오름차순
return o2[0] - o1[0]; // 첫 번째 숫자 기준 내림차순
return o1[1] - o2[1]; // 두 번째 숫자 기준 오름차순
return o2[1] - o1[1]; // 두 번째 숫자 기준 내림차순
// 실수형이면,
// return Double.compare(o1[1], o2[1]));
}
});
첫 번째 인자가 더 크면 양수를, 동일하면 0을, 두 번째 인자가 더 크면 음수를 리턴하도록 합니다. 또한, Comparator 인터페이스의 compare 함수의 return 값이 int형으로 선언되어 있다고 int형으로 형 변환하면 안됩니다.
int[][] arr = new int[][]{{1,2}, {2,4}, {2,1}, {3,5}, {3,2}, {4,4}}
// 첫 번째 숫자 기준 오름차순
Arrays.sort(arr, Comparator.comparingInt((int[] o) -> o[0]));
// 첫 번째 숫자 기준 내림차순
Arrays.sort(arr, Comparator.comparingInt((int[] o -> o[0]).reverse());
// 두 번째 숫자 기준 오름차순
Arrays.sort(arr, Comparator.comparingInt((int[] o -> o[1]));
// 두 번째 숫자 기준 내림차순
Arrays.sort(arr, Comparator.comparingInt((int[] o -> o[1]).reverse());
참고 자료