코딩 스쿨 Java

언어선택 : HTMLCSSJAVAJAVASCRIPTMYSQLSQL PHP

Java List Sorting

자바에서 리스트 정렬 (Java List Sorting): 개념 및 사용법

자바에서 **리스트(List)**를 정렬하는 방법은 매우 다양하며, 자바는 기본적으로 Collections 유틸리티 클래스와 ComparatorComparable 인터페이스를 사용하여 리스트의 정렬을 지원합니다. 기본적인 데이터 타입이나 사용자 정의 객체에 대해 오름차순 및 내림차순 정렬이 가능합니다.

1. 기본 데이터 타입 리스트 정렬

자바의 Collections.sort() 메서드를 사용하면 기본 데이터 타입(예: Integer, String 등)을 쉽게 정렬할 수 있습니다. 이 메서드는 리스트의 요소를 **오름차순(ascending order)**으로 정렬합니다.

1.1 Collections.sort()를 사용한 정렬

정수 리스트 정렬 예제

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(9);
        numbers.add(1);
        numbers.add(3);

        // 오름차순 정렬
        Collections.sort(numbers);

        System.out.println("Sorted List: " + numbers);  // 출력: [1, 2, 3, 5, 9]
    }
}

문자열 리스트 정렬 예제

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Orange");

        // 오름차순 정렬
        Collections.sort(fruits);

        System.out.println("Sorted List: " + fruits);  // 출력: [Apple, Banana, Mango, Orange]
    }
}

1.2 내림차순 정렬

내림차순으로 정렬하려면 Collections.sort() 메서드와 Collections.reverseOrder() 메서드를 함께 사용할 수 있습니다.

내림차순 정렬 예제

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(9);
        numbers.add(1);
        numbers.add(3);

        // 내림차순 정렬
        Collections.sort(numbers, Collections.reverseOrder());

        System.out.println("Sorted List in Descending Order: " + numbers);  // 출력: [9, 5, 3, 2, 1]
    }
}

2. 사용자 정의 객체 정렬

기본 데이터 타입이 아닌 사용자 정의 객체를 정렬하려면 Comparable 인터페이스 또는 Comparator 인터페이스를 구현해야 합니다.

2.1 Comparable 인터페이스를 사용한 정렬

Comparable 인터페이스는 객체의 기본적인 정렬 기준을 정의하는 데 사용됩니다. 예를 들어, Person 객체를 나이 순으로 정렬하려면 Comparable 인터페이스를 구현하고 compareTo() 메서드를 재정의해야 합니다.

Comparable을 사용한 정렬 예제

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

// Person 클래스가 Comparable 인터페이스를 구현
class Person implements Comparable<Person> {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 나이 기준으로 정렬 (오름차순)
    @Override
    public int compareTo(Person other) {
        return this.age - other.age;  // 나이순으로 오름차순 정렬
    }

    @Override
    public String toString() {
        return this.name + " (" + this.age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 20));

        // 나이순으로 정렬
        Collections.sort(people);

        System.out.println("Sorted by age: " + people);
        // 출력: [Bob (20), John (25), Alice (30)]
    }
}

2.2 Comparator 인터페이스를 사용한 정렬

Comparator 인터페이스는 Comparable과 달리, 여러 가지 기준으로 객체를 정렬할 수 있도록 커스텀 비교 로직을 제공합니다. Comparator를 사용하면 객체를 여러 가지 기준으로 정렬할 수 있습니다.

Comparator를 사용한 정렬 예제

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

// Person 클래스 (Comparable 구현 없음)
class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return this.name + " (" + this.age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 20));

        // 이름순으로 정렬 (Comparator 사용)
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return p1.name.compareTo(p2.name);
            }
        });

        System.out.println("Sorted by name: " + people);
        // 출력: [Alice (30), Bob (20), John (25)]
    }
}

2.3 Comparator를 사용한 여러 기준 정렬

Comparator를 사용하면 여러 기준으로 객체를 정렬할 수 있습니다. 예를 들어, 나이를 기준으로 정렬한 다음, 나이가 동일한 경우 이름을 기준으로 정렬할 수 있습니다.

여러 기준으로 정렬 예제

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return this.name + " (" + this.age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 20));
        people.add(new Person("Charlie", 20));

        // 나이순으로 정렬한 후, 같은 나이에서는 이름순으로 정렬
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                if (p1.age != p2.age) {
                    return p1.age - p2.age;  // 나이 기준 오름차순
                } else {
                    return p1.name.compareTo(p2.name);  // 이름 기준 오름차순
                }
            }
        });

        System.out.println("Sorted by age, then name: " + people);
        // 출력: [Bob (20), Charlie (20), Alice (25), John (25)]
    }
}

3. Stream API를 사용한 정렬 (Java 8 이상)

자바 8부터는 Stream API를 사용하여 리스트를 더 간편하게 정렬할 수 있습니다. Streamsorted() 메서드는 Comparator와 함께 사용할 수 있으며, 간결하게 정렬 작업을 수행할 수 있습니다.

Stream을 사용한 정렬 예제

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return this.name + " (" + this.age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 20));

        // Stream을 사용하여 나이 기준으로 정렬
        List<Person> sortedList = people.stream()
                .sorted(Comparator.comparingInt(person -> person.age))
                .collect(Collectors.toList());

        System.out.println("Sorted by age (using Stream): " + sortedList);
        // 출력: [Bob (20), John (25), Alice (30)]
    }
}

4. 요약

  • Collections.sort(): 리스트를 오름차

순 또는 내림차순으로 정렬할 수 있는 기본 메서드.

  • Comparable 인터페이스: 객체 자체에 정렬 기준을 정의할 때 사용.
  • Comparator 인터페이스: 여러 기준으로 정렬하거나, 동적으로 정렬 기준을 설정할 때 사용.
  • Stream API: 자바 8 이상에서 리스트를 간편하게 정렬할 수 있는 방법을 제공.

자바에서는 다양한 방식으로 리스트를 정렬할 수 있으며, 기본 제공되는 정렬 메서드들을 활용해 효율적인 코드 작성을 할 수 있습니다.


copyright ⓒ 스타트코딩 all rights reserved.
이메일 : startcodingim@gamil.com