본문 바로가기
자바

[자바] Stream .sorted() 활용

by kdohyeon (김대니) 2023. 2. 6.
반응형

자바 Stream 에서는 sorted() 함수를 제공한다.

예제

예시를 통해 알아보자. 검색한 키워드와 키워드별 횟수를 나타내는 객체이다. stats 리스트 객체에는 총 5개의 객체가 담겨있다. 이 리스트 객체를 활용해서 sorted() 함수에 사용해보자.

@Getter
public class BlogStatisticDto {
    private final String keyword;
    private final String count;

    @Builder
    public BlogStatisticDto(String keyword, String count) {
        this.keyword = keyword;
        this.count = count;
    }
}

public static void main(String[] args) {
    List<BlogStatisticDto> stats = Arrays.asList(
        new BlogStatisticDto("검색어1", 10),
        new BlogStatisticDto("검색어2", 5),
        new BlogStatisticDto("검색어3", 3),
        new BlogStatisticDto("검색어4", 7),
        new BlogStatisticDto("검색어5", 1),
    );
}

문제 1. count 를 기준으로 정렬 (ASC) 하기

  • Comparator 를 활용하여 정렬 기준을 부여할 수 있다.
  • BlogStatisticDto 의 count 변수를 기준으로 정렬한다.
  • 기본 정렬은 오름차순 (ASC) 이다.
public static void main(String[] args) {
    var sortedStats = stats.stream()
                            .sorted(Comparator.comparing(BlogStatisticDto::count))
                            .toList();
}

문제 2. count 를 기준으로 역정렬 (DESC) 하기

  • 역정렬은 Comparator.comparing().reversed() 를 활용하면 된다.
public static void main(String[] args) {
    var sortedStats = stats.stream()
                            .sorted(Comparator.comparing(BlogStatisticDto::count).reversed())
                            .toList();
}

문제 3. count, keyword 를 기준으로 복합 정렬하기

  • Comparator.comparing() 에서 1차 정렬 기준을 선정하고 .thenComparing() 을 통해 그 다음 정렬 기준을 설정할 수 있다.
public static void main(String[] args) {
    var sortedStats = stats.stream()
                            .sorted(Comparator.comparing(BlogStatisticDto::count)
                                                .thenComparing(BlogStatisticDto::keyword))
                            .toList();
}

 

반응형

댓글