Java/기본

[java] java stream sorted() 활용하기

vmpo 2021. 10. 1. 15:46

java stream sorted() 메소드 활용법에 대해 확인해보겠습니다.

 

java stream은 sorted()메소드로 쉽게 정렬이 가능합니다.

또한,두개 이상을 정렬 조건으로 걸어야할 때는 thenComparing()을 활용하면 됩니다.

 

아래 샘플코드로 테스트를 진행해보도록 하겠습니다.

public class Stock {

  int no;
  int price;
  String name;

  Stock(int price, String name) {
    this.price = price;
    this.name = name;
  }

  Stock(int no, int price, String name) {
    this.no = no;
    this.price = price;
    this.name = name;
  }

  public int getNo() {
    return no;
  }

  public void setNo(int no) {
    this.no = no;
  }

  public int getPrice() {
    return price;
  }

  public void setPrice(int price) {
    this.price = price;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

 

아래와 같이 리스트를 셋팅한 후 조건 별로 정렬해보도록 하겠습니다.

    List<Stock> list = new ArrayList<>();
    list.add(new Stock(1, 100000, "하이닉스"));
    list.add(new Stock(2, 400000, "네이버"));
    list.add(new Stock(2, 30000, "카카오뱅크"));
    list.add(new Stock(3, 110000, "카카오"));
    list.add(new Stock(4, 77000, "삼성전자"));

 

1.가격 순

    list.stream()
        .sorted(Comparator.comparing(Stock::getPrice))
        .map(Stock::getName)
        .forEach(System.out::println);

#출력결과

카카오뱅크
삼성전자
하이닉스
카카오
네이버

 

2.No 오름차순, 가격 오름차순

 

조건을 2개 이상 걸어야 할 때는 themComparing으로 앞의 조건이 동일할 경우 다음 조건을 걸어 정렬처리 가능하다.

    list.stream()
        .sorted(Comparator.comparing(Stock::getNo)
                          .thenComparing(Stock::getPrice))
        .map(Stock::getName)
        .forEach(System.out::println);

 

#출력결과

하이닉스
카카오뱅크
네이버
카카오
삼성전자

 

3.No 오름차순, 가격 내림차순

 

역순으로 정렬해야 할 때는 파라미터로 Comparator.reverseOrder()를 셋팅해주면 된다.

    list.stream()
        .sorted(Comparator.comparing(Stock::getNo)
                          .thenComparing(Stock::getPrice,Comparator.reverseOrder()))
        .map(Stock::getName)
        .forEach(System.out::println);

#출력결과

하이닉스
네이버
카카오뱅크
카카오
삼성전자

 

LIST