반응형

Java에서 기본적으로 Collections.sort를 이용하여 정렬 할 수 있다.

 

이때 Collections.sort를 이용하기 위해서는 이용하는 대상이 Collection 인터페이스를 implements 하고 있어야 한다.

 

 

기본 정렬 코드

import java.util.ArrayList;
import java.util.Collections;

public class Crocus {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        for(int i = 0 ; i < 30; i ++){
            list.add((int) (Math.random() * 100));
        }

        System.out.println("== 정렬 전 ==");
        System.out.println(list);

        Collections.sort(list);

        System.out.println("== 오름차순 정렬 ==");
        System.out.println(list);

        Collections.sort(list, Collections.reverseOrder());
        System.out.println("== 내림차순 정렬 ==");
        System.out.println(list);
    }
}

 

위 코드는 ArrayList를 정렬하는 코드이다.

 

Collections.sort를 통해 기본적으로 오름차순 정렬이 가능하고, Comparator 파라미터에 Collections.reverseOrder()을 넣으면 내림차순으로 정렬해준다.

 

(이때 그냥 오름차순 정렬 후, Collections.reverse(list)를 해줘도 내림차순과 동일하다.)

 


알고가기

 

이때 중요한 건 ArrayList가 과연 Collection 인터페이스를 구현하고 있는지가 중요하다.

 

ArrayList를 따라가보면 List<E>를 구현하고 있고 이 List<E>는 Collection<E>를 상속하고 있다.

 

따라서 우리는 Collection을 구현하고 있는 ArrayList를 Collections 내에 존재하는 메서드를 통해 이용 할 수 있다.

 

 


 

 

정렬 조건을 이용한 정렬

 

하나의 값만 정렬하면 쉽게 할 수 있지만 만약 여러 값을 동시에 정렬해야 한다면 어떻게 해야할까?

 

import java.util.ArrayList;

public class Crocus {
    public static void main(String[] args) {
        ArrayList<Score> scores = new ArrayList<>();

        for(int i = 0 ; i < 10; i ++){
            Score score = new Score((int) (Math.random() * 100), (int) (Math.random() * 100), (int) (Math.random() * 100));
            scores.add(score);
        }

        System.out.println("== 정렬 전 ==");
        for(Score i : scores){
            System.out.println("kor :: " + i.kor + " eng :: " + i.eng + " math :: " + i.math);
        }
    }

    static class Score {
        int kor;
        int eng;
        int math;

        public Score(int kor, int eng, int math) {
            this.kor = kor;
            this.eng = eng;
            this.math = math;
        }
    }
}

위와 같은 코드 처럼 3개의 값을 조건에 맞게 정렬해야 한다면 어떻게 해야할지 생각해보아야 한다.

 

이때 정렬 전인 상태는 위와 같고 만약 여기서 Collections.sort(scores)를 하면 어떻게 될까?

 

아래와 같이 에러를 발생시키면서 어떻게 정렬해야 할 지 모르겠으니 Comparable을 통해 정렬 조건을 만들어 달라고 한다.

 

 

 

정렬 조건을 이용한 정렬 코드

 

아래 코드는 3개의 데이터를 정렬하는 코드이다.

 

우선 Score class에 Comparable 인터페이스를 구현해주어 해당 클래스의 정렬 조건을 만들어준다.

 

정렬에 대한 내용은 아래 주석을 통해 달아두었다.

import java.util.ArrayList;
import java.util.Collections;

public class Crocus {
    public static void main(String[] args) {
        ArrayList<Score> scores = new ArrayList<>();

        for(int i = 0 ; i < 10; i ++){
            Score score = new Score((int) (Math.random() * 5), (int) (Math.random() * 5), (int) (Math.random() * 5));
            scores.add(score);
        }

        System.out.println("== 정렬 전 ==");
        for(Score i : scores){
            System.out.println("kor :: " + i.kor + " eng :: " + i.eng + " math :: " + i.math);
        }

        Collections.sort(scores);

        System.out.println("== 정렬 후 ==");
        for(Score i : scores){
            System.out.println("kor :: " + i.kor + " eng :: " + i.eng + " math :: " + i.math);
        }
    }

    static class Score implements Comparable<Score> {
        int kor;
        int eng;
        int math;

        public Score(int kor, int eng, int math) {
            this.kor = kor;
            this.eng = eng;
            this.math = math;
        }

        @Override
        public int compareTo(Score s) {
            // kor 점수를 내림차순으로
            if(this.kor < s.kor){
                return 1;
            } else if(this.kor == s.kor){
                // kor 점수가 같다면 eng 점수를 오름차순으로
                if(this.eng > s.eng){
                    return 1;
                } else if(this.eng == s.eng){
                    // eng 점수가 같다면 math 점수를 내림차순으로
                    if(this.math < s.math){
                        return 1;
                    } else {
                        return -1;
                    }
                } else {
                    return -1;
                }
            } else {
                return -1;
            }
        }
    }
}

 

 

 

 

반응형