[Java] 정렬 방법

hyunnzl·2025년 3월 7일

1. 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를 기준으로 오름차순 정렬





2. 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 기준 오름차순 정렬을 수행





3. 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 + 람다식 사용

0개의 댓글