Comparator, Comparable로 Sorting하기

이형석·2024년 5월 21일

알고리즘 Phase1

목록 보기
30/59

[Arrays.sort로 2차원배열을 정렬하는 예시]
Anonymous Object에서, Comparator의 compare() 오버라이딩 해주기
ex) int[n][2]인 2차원 배열을 0번째 행렬을 기준으로 재정렬하는 예

public class CompareToEX {
    public static void main(String[] args) {
        int n = 3;
        int[][] arr2D = new int[n][2];
        arr2D[0][0] = 3; arr2D[0][1] = 692;
        arr2D[1][0] = 1; arr2D[1][1] = 163;
        arr2D[2][0] = 2; arr2D[2][1] = 542;
        Arrays.sort(arr2D, (o1, o2) -> {
        	return o1[0] - o2[0];	//0번째 행렬을 기준으로 정렬, 1번째 행렬이 기준이면 o1[1] - o2[1]
        });
        for (int i = 0; i < 3; i++) {
            System.out.println(arr2D[i][0]);
        }
    }
}

출력순서 1 2 3
+ 참고로 Arrays.sort()에서 기본형변수타입(int, String 등)의 1차원 배열 정렬기준을 재정의는 불가능, 기본형변수타입의 Comparator는 이미 구현되어 있음

[Arrays.sort로 객체 배열을 정렬하는 예시]
Anonymous Object에서, Comparator의 compare() 오버라이딩 해주기
ex)

public class ComparableEX{
	public static void main(String[] args){
    	Student[] students = new Student[3];
        //student객체 3개 생성하는 코드 생략
        Arrays.sort(students, (o1, o2) -> {
        	return o1.age - o2.age
		});
    }
    static class Student{
        String name;
	   	int age;
	}
}

[Collections.sort로 Collection객체를 정렬하는 예시]
Anonymous Object에서, Comparator의 compare() 오버라이딩 해주기
ex)
int start, int end라는 데이터멤버를 가진 Meeting이라는 객체가 있다.
이 "회의"객체를 시작시간을 기준으로 정렬하려고 한다.
1. 일단 List에 객체를 담는다.
2-1. Collections.sort를 호출하는데, 두번째 parameter로 Comparator객체를 전달한다.
2-2. 이때 제네릭타입에 정렬할 객체를 넣는다.
3-1. Comparator객체를 Anonymous객체로 바로 정의해준다.(compare()함수를 오버라이딩 한다.)
3-2. 정렬기준인 데이터멤버를 비교해 중 오른쪽이 크면 -1을 return, 왼쪽이 크면 1을 return, 같으면 0을 return하도록 한다.

public class CompareToEX {
    public static void main(String[] args) {
        List<Meeting> meetings = new ArrayList<>();
        meetings.add(new Meeting(1, 10));
        meetings.add(new Meeting(3, 6));
        meetings.add(new Meeting(2, 7));
        Collections.sort(meetings, new Comparator<Meeting>() {
            @Override
            public int compare(Meeting o1, Meeting o2) {
  				//Meeting객체의 start를 기준으로 정렬
                if (o1.start < o2.start) {	//오른쪽이 크면 -1을 return
                    return -1;
                } else if (o1.start > o2.start) {	//왼쪽이 크면 1을 return
                    return 1;
                }else return 0;	//같으면 0을 return
            }
        });
        Iterator<Meeting> it = meetings.iterator();
        while (it.hasNext()) {
            System.out.println(it.next().start);
        }
    }
    static class Meeting{
        int start;
        int end;
        public Meeting(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }
}

출력 순서는 1 2 3

더 간략하게 람다 함수로 구현한 예시

Collections.sort(meetings, ((o1, o2) -> {
	if (o1.start < o2.start) {
		return -1;
	} else if (o1.start > o2.start) {
		return 1;
	}else return 0;
}));

더 간단한 표현식

Collections.sort(meetings, ((o1, o2) -> {
	return o1 - o2;
}));

* 오름차순

참고

Comparator, Comparable 둘다 Interface

  • Comparator : 파라미터 2개 비교
    ex) compare(T o1, T o2)
  • Comparable : 자신과 비교
    ex) compareTo(T o)

  • Comparator : sort()의 두 번째 파라미터로 사용됨
  • Comparable : 클래스에서 오버라이딩으로 사용됨
profile
금융IT 개발자

0개의 댓글