Skip to main content

Java Stream 정렬


1. 기본 정렬 (숫자 오름차순)

List<Integer> list = Arrays.asList(5, 3, 1, 4);
List<Integer> sorted = list.stream()
    .sorted()
    .collect(Collectors.toList());

2. 내림차순 정렬

List<Integer> sortedDesc = list.stream()
    .sorted(Comparator.reverseOrder())
    .collect(Collectors.toList());

3. 객체 리스트 정렬

List<Person> people = Arrays.asList(
    new Person("Alice", 25),
    new Person("Bob", 20)
);

// 나이 기준 오름차순
List<Person> sortedPeople = people.stream()
    .sorted(Comparator.comparing(p -> p.age))
    .collect(Collectors.toList());

4. 여러 기준으로 정렬

// 나이 기준, 같으면 이름 기준
.sorted(Comparator.comparing(Person::getAge)
                 .thenComparing(Person::getName))