[JAVA] ArrayList 정렬하기 (ArrayList sort)

[JAVA] ArrayList 정렬하기 (ArrayList sort)

자바에서 ArrayList 를 오름차순으로 정렬하려면 Collections.sort 명령어를 사용하면 된다.

ArrayList<String> tempList = new ArrayList<String>();

tempList.add(“테스트3”);

tempList.add(“테스트4”);

tempList.add(“테스트2”);

tempList.add(“테스트1”);

tempList.add(“abcdefg”);

tempList.add(“0123456789”);

// 리스트를 오름차순으로 정렬

Collections.sort(tempList);

System.out.println(tempList);

결과는 아래와 같이 나온다.

[0123456789, abcdefg, 테스트1, 테스트2, 테스트3, 테스트4]

ArrayList를 오름차순이 아닌 다른 조건으로 정렬하려면 Comparator 인터페이스를 사용하면 된다.

// Comparator 인터페이스를 구현하여 리스트를 정렬

Collections.sort(tempList, new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        return 0;
    }

});

compare 메서드를 구현(임플리먼트)할 때, 0 을 리턴하면 순서가 바뀌지 않는다.

정확히 설명하면 두 값이 같다면 0을 반환하고, 첫 번째 값이 크다면 양수(1)를, 두 번째 인자가 크다면 음수(-1)를 반환하면 된다.

compare 메서드 안에 원하는 조건식을 넣으면 된다.

위 코드처럼 무조건 0 을 리턴하면 순서가 바뀌지 않은 상태 그대로이다.

만약 ArrayList 의 제네릭이 String이 아닌 경우라면 (ex : ArrayList<Integer>) 아래와 같이 제네릭 타입만 바꿔주면 된다.

// Comparator 인터페이스를 구현하여 리스트를 정렬

Collections.sort(tempList, new Comparator<Integer>() {

    @Override
    public int compare(Integer o1, Integer o2) {
        return 0;
    }
});

예를 들어 제네릭이 Integer 인 ArrayList의 내림차순 정렬은 아래처럼 한다.

ArrayList<Integer> tempList = new ArrayList<Integer>();

tempList.add(1);
tempList.add(5);
tempList.add(7);
tempList.add(5);
tempList.add(99);
tempList.add(-200);

// 리스트를 내림차순으로 정렬
Collections.sort(tempList, new Comparator<Integer>() {

    @Override
    public int compare(Integer o1, Integer o2) {
        // 순서를 바꾼다.
        if (o1 < o2) {
            return 1;
        } else {

            return -1;

        }
    
        return 0;
    }
});
  
System.out.println(tempList);

결과는 아래와 같다.

[99, 7, 5, 5, 1, -200]

관련글: [JAVA] 제네릭이 String 인 ArrayList 정렬하기 (ArrayList sort / String sort) (https://blog.naver.com/bb_/222033828409)