[Java] Arrays.sort 와 Collections.sort 정리

2022. 12. 12. 14:18 JAVA/Java

Arrays.sort

 

오름차순

기본 오름차순 정렬 : 숫자 - 대문자 - 소문자 - 한글 순서로 정렬

 

import java.util.Arrays;

public class Sort {
	public static void main(String[] args) {
		String[] str = {"a", "1", "가", "A", "3", "나"};

		for(String s : str) {	// 정렬 전 출력
			System.out.print(s + " ");
		}
		System.out.println();

		Arrays.sort(str);	// 정렬 후 출력
		for(String s : str) {
			System.out.print(s + " ");
		}
	}
}

 

a 1 가 A 3 나
1 3 A a 가 나

 

 

내림차순

한글 - 소문자 - 대문자 - 숫자 순서로 정렬

 

import java.util.Arrays;
import java.util.Collections;

public class Sort {
	public static void main(String[] args) {
		String[] str = {"a", "1", "가", "A", "3", "나"};

		for(String s : str) {	// 정렬 전 출력
			System.out.print(s + " ");
		}
		System.out.println();

		Arrays.sort(str, Collections.reverseOrder());	// 정렬 후 출력
		for(String s : str) {
			System.out.print(s + " ");
		}
	}
}

 

나 3 A 가 1 a
나 가 a A 3 1

 

 

 

Collections.sort   Collections.reverse

 

Array와 동일하게 오름차순 : 한글 - 소문자 - 대문자 - 숫자 순서로 정렬하고

내림차순 : 숫자 - 대문자 - 소문자 - 한글 순서로 정렬

 

import java.util.Arrays;
import java.util.Collections;

public class Sort {
	public static void main(String[] args) {    
		String[] str = {"a", "1", "가", "A", "3", "나"};
		List<String> list = Arrays.asList(str);	// 테스트를 위해..        

		System.out.println(list.toString());	// 정렬 전 출력
		
		Collections.sort(list);
		System.out.println(list.toString());	// 오름차순 정렬 후 출력
        
		Collections.reverse(list);        
		System.out.println(list.toString());	// 내림차순 정렬 후 출력
	}
}

 

 

Comparable Interface

class Student {
	String name;
	int score;
}

숫자나 문자의 정렬이 아닌, 새롭게 정의한 클래스가 있을 때, 어떤 값을 기준으로 정렬을 할 지 판단해야한다.

 

이 때 기준을 잡아주는 것이 Comparable Interface 이고, 이 인터페이스를 구현할 클래스는 정렬을 하고자 할 때 정렬이 가능한 클래스가 된다.

 

import java.util.*;

class Student implements Comparable {
	String name;
	int score;

	Student (String name, int score) {
		this.name = name;
		this.score = score;
	}

	@Override	
	public int compareTo(Object o) {
		Student other = (Student) o;	// 비교할 다른 Student 객체
		return other.score - this.score;	// 다른 학생과 이 학생의 score 비교 정렬
	}
}

public class Test {
	public static void main(String[] args) {
		List<Student> list = new ArrayList<>();
		list.add(new Student("han", 20));
		list.add(new Student("lee", 15));
		list.add(new Student("kim", 8));
		list.add(new Student("bae", 11));

		Collections.sort(list);
	}
}

 

compareTo 에서 other.score - this.score 반환 값의 의미는 다음과 같다.

 

양수 : other > this

0    : other == this

음수 : other < this

 

하지만, compareTo 메소드는 이미 정의되어있는 클래스를 상속받아 재정의하는 비효율적인 면이 있다.

만약 comparable에 의해 이름으로 정렬 기준이 잡혀있고 sort 메서드를 사용한다면 사전순으로 정렬을 한다.

이 이름 정렬의 기준을 남겨놓고, 새로운 정렬기준을 하나 더 추가하여 쓰고 싶을 때마다 compareTo 메소드를 재정의 하는 것은 번거롭다. 이럴 때 사용하는 것이 Comparator 인터페이스이다.

 

 

Collections.sort

Collections.sort(list, comparator); 의 형태로 사용한다.

comparable 나(this)를 기준으로 comapreTo 메소드에 상대를 넣어 비교를 했다면,

comparator 비교대상 2개를 가지고 판단을 한다.

int compare(T o1, T o2) 로 두 객체의 특정 값을 연산해서 음수가 나오면, o1의 객체가 작다고 판단, 양수가 나오면 o2의 객체가 작다고 판단한다.

 

import java.util.*;

class Student implements Comparable {
	String name;
	int score;

	Student (String name, int score) {
		this.name = name;
		this.score = score;
	}
}

public class Test {
	public static void main(String[] args) {
		List<Student> list = new ArrayList<>();
		list.add(new Student("han", 20));
		list.add(new Student("lee", 15));
		list.add(new Student("kim", 8));
		list.add(new Student("bae", 11));

		Collections.sort(list, new Comparator<Student>() {
			@Override
			public int compare(Student s1, Student s2) {
				return s1.score - s2.score;
			}
		});
        
        
	}
}

 

출처 : https://haenny.tistory.com/349