Java에서 배열을 정렬하는데 사용된다. 이 메서드는 다양한 데이터 유형에 대해 오버로딩되어 있으며, 배열의 요소를 정렬하여 그 값을 증가하는 순서로 재배열한다.
원시 자료형 배열 정렬 : int, long, float, double 등의 원시 자료형 배열에 대해서도 정렬이 가능하다.
참조 자료형 배열 정렬 : 객체 배열도 정렬할 수 있다. 이 때 객체는 Comparable 인터페이스를 구현해야한다.
정렬 방향 변경 : Arrays.sort()는 기본적으로 오름차순으로 정렬하지만, Comparator를 지정하여 내림차순으로도 정렬할 수 있다.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers); // 오름차순 정렬
System.out.println(Arrays.toString(numbers)); // [1, 2, 5, 8, 9]
// 내림차순 정렬을 위한 Comparator 사용
Integer[] numbers2 = {5, 2, 8, 1, 9};
Arrays.sort(numbers2, (a, b) -> b - a);
System.out.println(Arrays.toString(numbers2)); // [9, 8, 5, 2, 1]
int[] index = {0, 1, 2};
//정렬 규칙을 사용하여 정렬할 수 있다.
Arrays.sort(index, (a, b) -> {
int scoreA = scores[a][0] + scores[a][1];
int scoreB = scores[b][0] + scores[b][1];
if (scoreA != scoreB) {
return scoreB - scoreA; // 총점이 높은 순서
} else if (hasHardProblem && scores[a][hardProblem] != scores[b][hardProblem]) {
return scores[b][hardProblem] - scores[a][hardProblem]; // 어려운 문제에서 높은 점수 순서
} else {
return a - b; // ID가 낮은 순서
}
});
}
}
기본적으로 오름차순 즉, 낮은 순으로 정렬하려면 return a-b
내림차순 즉, 높은 순으로 정렬하려면 return b-a 를 해야한다.
2번에 대해서 예시를 들자면,
public class Person implements Comparable<Person> {
//Comparable 인터페이스를 implements한다.
private String name;
private int age;
// 생성자, getter, setter 등은 생략
@Override
public int compareTo(Person otherPerson) {
// 나이에 대한 비교
// 오름차순으로 비교
return this.age - otherPerson.age;
//내림차순으로 비교 -> return otherPerson.age - this.age;
}
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Person[] people = {
new Person("Alice", 25),
new Person("Bob", 20),
new Person("Charlie", 30)
};
Arrays.sort(people);
for (Person person : people) {
System.out.println(person.getName() + ": " + person.getAge());
-> Bob - Alice - Charlie 순으로 정렬됨
}
}
}
여기서 의문이 들었던 게 그럼 Collections.sort() 랑 무슨 차이인 거지? 라는 생각이 들었다. 그래서 찾아본 결과, Collections.sort() 는 컬렉션을 정렬하는데 사용되는 메서드이다.
Arrays.sort() 와 유사하지만 배열이 아닌 컬렉션을 정렬하는 데 차이점이 있다.
-Java에서 컬렉션을 정렬하는데 사용되는 메서드
-List, Set, Queue 등의 컬렉션 인터페이스를 구현한 모든 클래스에 대해 사용할 수 있다.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
numbers.add(9);
Collections.sort(numbers); // 오름차순 정렬
System.out.println(numbers); // [1, 2, 5, 8, 9]
// 내림차순 정렬
Collections.sort(numbers, Collections.reverseOrder());
System.out.println(numbers); // [9, 8, 5, 2, 1]
}
}
Collections.sort() 에는 Arrays.sort() 와 다르게 내림차순을 바로 쓸 수 있는 Comparator 인터페이스를 구현한 클래스가 있어 사용할 수 있다.
-> Collections.reverseOrder()
Arrays.sort() 나 Collections.sort()를 사용하여 오름차순이 아닌 다른 정렬 방식을 적용하려면, 사용자 정의 정렬 기준에 맞는 Comparator를 제공해야 한다.
public class Main {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 20));
people.add(new Person("Charlie", 30));
// Comparator를 사용하여 나이를 기준으로 내림차순으로 정렬
Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge).reversed();
Collections.sort(people, ageComparator);
// 정렬된 결과 출력
for (Person person : people) {
System.out.println(person.getName() + ": " + person.getAge());
}
}
}
public class Main {
public static void main(String[] args) {
Integer[] numbers = {5, 2, 8, 1, 9};
// Comparator를 사용하여 역순으로 정렬
Comparator<Integer> reverseOrder = (a, b) -> b - a;
Arrays.sort(numbers, reverseOrder);
System.out.println(Arrays.toString(numbers)); // [9, 8, 5, 2, 1]
}
}