✔️ Comparable
- 목적: 자기 자신과 매개변수 객체를 비교
- 구현 방법: Comparable 인터페이스를 구현하는 클래스는 compareTo 메서드를 오버라이드
import java.util.*;
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person other) {
// 오름차순 정렬
return this.age - other.age;
// 내림차순 정렬
// return other.age - this.age;
}
@Override
public String toString() {
return name + " - " + age;
}
}
import java.util.*;
class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 오름차순 정렬
Collections.sort(people);
for (Person person : people) {
System.out.println(person);
}
// 내림차순 정렬
Collections.sort(people, Collections.reverseOrder());
for (Person person : people) {
System.out.println(person);
}
}
}
❗️ Comparable 인터페이스를 구현한 객체는 이미 기본 정렬 기준을 가지고 있다. 따라서 Collection의 sort(List<T> list) 메서드를 호출하면 기본 정렬 기준에 따라 정렬된다.
✔️ Comparator
- 목적: 두 매개변수 객체를 비교
- 구현 방법: Comparator 인터페이스를 구현하는 클래스는 compare 메서드를 오버라이드
1️⃣ Person 클래스 자체가 Comparator<Person>를 구현하여 정렬 기준을 정의
import java.util.*;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name + " - " + age;
}
}
import java.util.*;
class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
// 오름차순 정렬
return p1.getAge() - p2.getAge();
// 내림차순 정렬
// return p2.getAge() - p1.getAge();
}
}
import java.util.*;
class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
PersonComparator personComparator = new PersonComparator();
Collections.sort(people, personComparator);
for (Person person : people) {
System.out.println(person);
}
// 내림차순 정렬 (Comparator의 구현만 바꾸면 됩니다)
Collections.sort(people, Collections.reverseOrder(personComparator));
for (Person person : people) {
System.out.println(person);
}
}
}
2️⃣ Person 클래스 외부에서 익명 클래스를 사용하여 Comparator<Person>를 인라인으로 정의하여 정렬 기준을 제공
import java.util.*;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name + " - " + age;
}
}
import java.util.*;
class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 익명 클래스를 사용하여 Comparator 구현
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
// 오름차순 정렬
return p1.getAge() - p2.getAge();
}
});
System.out.println("오름차순 정렬:");
for (Person person : people) {
System.out.println(person);
}
// 내림차순 정렬
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
// 내림차순 정렬
return p2.getAge() - p1.getAge();
}
});
System.out.println("내림차순 정렬:");
for (Person person : people) {
System.out.println(person);
}
}
}
❗️ Comparator를 이용하면 외부에서 정렬 기준을 지정할 수 있다. 이 경우 Collection의 sort(List<T> list, Comparator<? super T> c) 메서드를 사용하여 정렬 기준을 함께 제공해야 한다.
3️⃣ 익명 클래스를 람다 표현식으로 더 간결하게 표현
import java.util.*;
class Main{
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 람다 표현식을 사용하여 Comparator 구현
Collections.sort(people, (p1, p2) -> p1.getAge() - p2.getAge()); // 오름차순 정렬
for (Person person : people) {
System.out.println(person);
}
}
}
'CS > JAVA' 카테고리의 다른 글
[Java] String (Array) <-> Int (Array) 변환 정리 (1) | 2024.07.03 |
---|---|
[Java] Java Record 이것의 정체 (3) | 2023.11.12 |
[Java] Java의 compareTo 메소드와 Comparable 인터페이스 (0) | 2023.07.25 |
[Java] String, Char 대소문자 확인 및 변환 (0) | 2023.02.27 |
[JAVA] String <->Char 변환 정리 (0) | 2023.02.27 |