Comparable 인터페이스 사용Comparable 인터페이스를 구현하면 해당 클래스의 기본 정렬 기준을 정의할 수 있다.
score 기준으로 오름차순 정렬import java.util.ArrayList;
import java.util.Collections;
class Student implements Comparable<Student> {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.score, other.score); // 오름차순 정렬
}
@Override
public String toString() {
return name + ": " + score;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Alice", 90));
students.add(new Student("Bob", 85));
students.add(new Student("Charlie", 95));
Collections.sort(students); // Comparable 기준 정렬
System.out.println(students);
}
}
[Bob: 85, Alice: 90, Charlie: 95]
compareTo 메서드에서 Integer.compare(this.score, other.score)를 사용하여 score를 기준으로 오름차순 정렬Comparator 인터페이스 사용Comparator 인터페이스를 활용하면 여러 정렬 기준을 만들 수 있다.
name 기준으로 정렬import java.util.*;
class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return name + ": " + score;
}
}
class NameComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name); // 이름 기준 오름차순 정렬
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Alice", 90));
students.add(new Student("Bob", 85));
students.add(new Student("Charlie", 95));
Collections.sort(students, new NameComparator()); // Comparator 기준 정렬
System.out.println(students);
}
}
[Alice: 90, Bob: 85, Charlie: 95]
Comparator를 이용해 name 기준 오름차순 정렬을 수행Comparator 익명 클래스 또는 람다 사용Comparator를 직접 정의하지 않고, 익명 클래스 또는 람다식을 사용하여 정렬할 수도 있다.
score 기준 내림차순 정렬 (람다식 활용)import java.util.*;
class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return name + ": " + score;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Alice", 90));
students.add(new Student("Bob", 85));
students.add(new Student("Charlie", 95));
// 내림차순 정렬 (람다식 사용)
students.sort((s1, s2) -> Integer.compare(s2.score, s1.score));
System.out.println(students);
}
}
[Charlie: 95, Alice: 90, Bob: 85]
Collections.sort() 대신 students.sort()를 활용하여 가독성을 높임Comparator 구현 없이 람다식으로 간결하게 작성Comparable (compareTo 메서드 오버라이드) 사용Comparator 인터페이스 사용Comparator + 람다식 사용