고급 정렬 기법
실제 응용 프로그램에서는 다음과 같은 더 복잡한 정렬 로직이 필요한 경우가 많습니다.
- 여러 기준별 정렬 (예: GPA 별 정렬, GPA 가 같으면 이름별 정렬)
- 역순 정렬
- 사용자 정의 comparator 체인 생성
이러한 고급 기술을 살펴보겠습니다.
여러 기준별 정렬
~/project 디렉토리에 MultiCriteriaDemo.java라는 새 파일을 만듭니다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MultiCriteriaDemo {
public static void main(String[] args) {
// Create a list of students with some having the same GPA
List<Student> students = new ArrayList<>();
students.add(new Student("John", 3.5, 101));
students.add(new Student("Mary", 3.8, 102));
students.add(new Student("Alice", 3.5, 103)); // Same GPA as John
students.add(new Student("Bob", 3.8, 104)); // Same GPA as Mary
students.add(new Student("Charlie", 3.2, 105));
// Print the unsorted list
System.out.println("Unsorted Student List:");
for (Student student : students) {
System.out.println(student);
}
// Sort first by GPA, then by name
Comparator<Student> byGpa = Comparator.comparing(Student::getGpa);
Comparator<Student> byName = Comparator.comparing(Student::getName);
// Combine the comparators using thenComparing
Comparator<Student> byGpaThenName = byGpa.thenComparing(byName);
// Sort the list
Collections.sort(students, byGpaThenName);
// Print the sorted list
System.out.println("\nStudents sorted by GPA, then by name:");
for (Student student : students) {
System.out.println(student);
}
}
}
이 프로그램은 다음을 수행합니다.
-
일부 학생이 동일한 GPA 를 갖는 학생 목록을 생성합니다.
-
GPA 에 대한 comparator 와 이름에 대한 comparator 를 생성합니다.
-
thenComparing() 메서드를 사용하여 이러한 comparator 를 결합합니다.
-
먼저 GPA 별로, GPA 가 같으면 이름별로 학생을 정렬합니다.
-
코드를 컴파일하고 실행합니다.
cd ~/project
javac Student.java MultiCriteriaDemo.java
java MultiCriteriaDemo
다음과 유사한 출력을 볼 수 있습니다.
Unsorted Student List:
John, GPA: 3.5, Reg No: 101
Mary, GPA: 3.8, Reg No: 102
Alice, GPA: 3.5, Reg No: 103
Bob, GPA: 3.8, Reg No: 104
Charlie, GPA: 3.2, Reg No: 105
Students sorted by GPA, then by name:
Charlie, GPA: 3.2, Reg No: 105
Alice, GPA: 3.5, Reg No: 103
John, GPA: 3.5, Reg No: 101
Bob, GPA: 3.8, Reg No: 104
Mary, GPA: 3.8, Reg No: 102
GPA 가 같은 학생 (Alice 와 John 은 3.5, Bob 과 Mary 는 3.8) 이 알파벳순으로 정렬되는 것을 확인하십시오.
역순 정렬
~/project 디렉토리에 ReverseOrderDemo.java라는 새 파일을 만듭니다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ReverseOrderDemo {
public static void main(String[] args) {
// Create a list of students
List<Student> students = new ArrayList<>();
students.add(new Student("John", 3.5, 101));
students.add(new Student("Mary", 3.8, 102));
students.add(new Student("Alice", 3.2, 103));
students.add(new Student("Bob", 3.9, 104));
students.add(new Student("Charlie", 3.0, 105));
// Print the unsorted list
System.out.println("Unsorted Student List:");
for (Student student : students) {
System.out.println(student);
}
// Method 1: Using Collections.reverseOrder() with a comparator
Comparator<Student> byGpa = Comparator.comparing(Student::getGpa);
Comparator<Student> byGpaReversed = Collections.reverseOrder(byGpa);
Collections.sort(students, byGpaReversed);
System.out.println("\nStudents sorted by GPA in descending order (Method 1):");
for (Student student : students) {
System.out.println(student);
}
// Method 2: Using the reversed() method of Comparator
Collections.sort(students, Comparator.comparing(Student::getName).reversed());
System.out.println("\nStudents sorted by name in reverse alphabetical order (Method 2):");
for (Student student : students) {
System.out.println(student);
}
}
}
이 프로그램은 역순으로 정렬하는 두 가지 방법을 보여줍니다.
-
Collections.reverseOrder()를 사용하여 comparator 를 반전시킵니다.
-
comparator 의 reversed() 메서드를 사용합니다.
-
코드를 컴파일하고 실행합니다.
cd ~/project
javac Student.java ReverseOrderDemo.java
java ReverseOrderDemo
다음과 유사한 출력을 볼 수 있습니다.
Unsorted Student List:
John, GPA: 3.5, Reg No: 101
Mary, GPA: 3.8, Reg No: 102
Alice, GPA: 3.2, Reg No: 103
Bob, GPA: 3.9, Reg No: 104
Charlie, GPA: 3.0, Reg No: 105
Students sorted by GPA in descending order (Method 1):
Bob, GPA: 3.9, Reg No: 104
Mary, GPA: 3.8, Reg No: 102
John, GPA: 3.5, Reg No: 101
Alice, GPA: 3.2, Reg No: 103
Charlie, GPA: 3.0, Reg No: 105
Students sorted by name in reverse alphabetical order (Method 2):
Mary, GPA: 3.8, Reg No: 102
John, GPA: 3.5, Reg No: 101
Charlie, GPA: 3.0, Reg No: 105
Bob, GPA: 3.9, Reg No: 104
Alice, GPA: 3.2, Reg No: 103
첫 번째 정렬은 GPA 별로 내림차순으로 학생을 보여주고, 두 번째 정렬은 이름별로 역 알파벳순으로 학생을 보여줍니다.
복잡한 정렬 체인
- 여러 기준과 역순 정렬을 결합하는 또 다른 예제를 만들어 보겠습니다.
~/project 디렉토리에 ComplexSortingDemo.java라는 파일을 만듭니다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComplexSortingDemo {
public static void main(String[] args) {
// Create a list of students with varied data
List<Student> students = new ArrayList<>();
students.add(new Student("John", 3.5, 101));
students.add(new Student("Mary", 3.8, 102));
students.add(new Student("Alice", 3.5, 103)); // Same GPA as John
students.add(new Student("Bob", 3.8, 104)); // Same GPA as Mary
students.add(new Student("Charlie", 3.2, 105));
students.add(new Student("David", 3.2, 106)); // Same GPA as Charlie
// Print the unsorted list
System.out.println("Unsorted Student List:");
for (Student student : students) {
System.out.println(student);
}
// Create a complex sorting chain:
// 1. Sort by GPA in descending order
// 2. If GPAs are equal, sort by name in ascending order
// 3. If names are also equal, sort by registration number in descending order
Comparator<Student> complexComparator = Comparator
.comparing(Student::getGpa, Comparator.reverseOrder())
.thenComparing(Student::getName)
.thenComparing(Student::getRegNo, Comparator.reverseOrder());
Collections.sort(students, complexComparator);
System.out.println("\nStudents sorted by complex criteria:");
System.out.println("(GPA descending, then name ascending, then reg. number descending)");
for (Student student : students) {
System.out.println(student);
}
}
}
이 프로그램은 다음을 수행하는 복잡한 정렬 체인을 생성합니다.
-
먼저 GPA 별로 내림차순으로 학생을 정렬합니다.
-
GPA 가 같으면 이름별로 오름차순으로 정렬합니다.
-
GPA 와 이름이 모두 같으면 등록 번호별로 내림차순으로 정렬합니다.
-
코드를 컴파일하고 실행합니다.
cd ~/project
javac Student.java ComplexSortingDemo.java
java ComplexSortingDemo
다음과 유사한 출력을 볼 수 있습니다.
Unsorted Student List:
John, GPA: 3.5, Reg No: 101
Mary, GPA: 3.8, Reg No: 102
Alice, GPA: 3.5, Reg No: 103
Bob, GPA: 3.8, Reg No: 104
Charlie, GPA: 3.2, Reg No: 105
David, GPA: 3.2, Reg No: 106
Students sorted by complex criteria:
(GPA descending, then name ascending, then reg. number descending)
Bob, GPA: 3.8, Reg No: 104
Mary, GPA: 3.8, Reg No: 102
Alice, GPA: 3.5, Reg No: 103
John, GPA: 3.5, Reg No: 101
Charlie, GPA: 3.2, Reg No: 105
David, GPA: 3.2, Reg No: 106
이 출력에서:
- Bob 과 Mary 는 모두 GPA 가 3.8 이지만 Bob 이 알파벳순으로 먼저 옵니다.
- Alice 와 John 은 모두 GPA 가 3.5 이지만 Alice 가 알파벳순으로 먼저 옵니다.
- Charlie 와 David 는 모두 GPA 가 3.2 이고 Charlie 가 알파벳순으로 먼저 옵니다.
이것은 comparator 를 연결하여 복잡하고 다단계 정렬 로직을 생성할 수 있는 방법을 보여줍니다.