본문 바로가기

프로젝트 & TIL/일별 공부 기록 (백엔드 스쿨)

54일차 - stream 정렬

stream을 이용한 정렬

* 기본 정렬(오름차순)

  

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

 

* 내림차순 정렬

  

List<Integer> list = List.of(5, 2, 3, 4, 1);
list = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); // 5, 4, 3, 2, 1

stream을 이용한 객체 정렬

* 기본 정렬(오름차순)

  

List<Person> list = List.of(
            new Person("yuri", 30),  // String name, int age
            new Person("hyeni", 31),
            new Person("may", 9));
list = list.stream()
       .sorted(Comparator.comparing(Person::getAge))
       .collect(Collectors.toList()); // may, yuri, hyeni

  

* 내림차순 정렬

  

List<Person> list = List.of(
            new Person("yuri", 30),  // String name, int age
            new Person("hyeni", 31),
            new Person("may", 9));
list = list.stream()
       .sorted(Comparator.comparing(Person::getAge).reversed())
       .collect(Collectors.toList()); // hyeni, yuri, may