Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Java/자바] 리스트 정렬하는 3가지 방법 본문
리스트 정렬 방법
Java에서 리스트를 정렬하는 것은 매우 일반적인 작업입니다. 이번 글에서는 Java에서 리스트를 정렬하는 세 가지 방법을 살펴보겠습니다.
1. Collections.sort() 메서드 사용
Collections 클래스의 sort() 메서드를 사용하여 리스트를 정렬할 수 있습니다. 이 메서드는 리스트를 직접 변경하므로 원본 리스트의 요소 순서가 변경됩니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
List numbers = new ArrayList<>(Arrays.asList(3, 1, 2));
Collections.sort(numbers);
System.out.println("정렬된 리스트: " + numbers);
}
}
출력:
정렬된 리스트: [1, 2, 3]
2. Comparable 인터페이스 구현
Comparable 인터페이스를 구현하여 객체의 natural ordering을 정의할 수 있습니다. 이 방법은 객체의 클래스 정의를 변경해야 하므로 클래스의 소스 코드에 접근할 수 있는 경우에 사용합니다.
import java.util.*;
public class Person implements Comparable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return this.age - other.age;
}
public String toString() {
return this.name + " (" + this.age + ")";
}
public static void main(String[] args) {
List people = new ArrayList<>(Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 20)
));
Collections.sort(people);
System.out.println("정렬된 리스트: " + people);
}
}
출력:
정렬된 리스트: [Charlie (20), Alice (25), Bob (30)]
3. Comparator 인터페이스 사용
Comparator 인터페이스를 구현하여 정렬 기준을 지정할 수 있습니다. 이 방법은 객체의 natural ordering을 변경하거나 클래스를 수정할 수 없는 경우에 사용됩니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
List names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
Collections.sort(names, Comparator.reverseOrder());
System.out.println("정렬된 리스트: " + names);
}
}
출력:
정렬된 리스트: [Charlie, Bob, Alice]
'프로그래밍' 카테고리의 다른 글
[Java/자바] List 인터페이스: 데이터 구조 다루기 (0) | 2024.03.09 |
---|---|
[Java/자바] ArrayList로 데이터 관리하기 (0) | 2024.03.09 |
[Java/자바] HashSet 정렬하는 3가지 방법 (0) | 2024.03.08 |
[Java/자바] 리스트 정렬하는 3가지 방법 (0) | 2024.03.08 |
[Java/자바] 2차원 배열 선언 및 출력 방법 (0) | 2024.03.08 |