1. 기본정렬
  2. 역순정렬
  3. null포함(nullLast)
  4. null포함(nullFirst)

1.기본 정렬

List<Member> list = List.of(Member.of(10), Member.of(20), Member.of(30));

List<Member> result = list.stream()
    .sorted(Comparator.comparing(Member::getAge))
    .collect(Collectors.toList());

System.out.println(result);

결과

[Member{age=10}, Member{age=20}, Member{age=30}]

2.역순 정렬

List<Member> list = List.of(Member.of(10), Member.of(20), Member.of(30));

List<Member> result = list.stream()
     .sorted(Comparator.comparing(Member::getAge, Comparator.reverseOrder()))
     .collect(Collectors.toList());

System.out.println(result);

결과

[Member{age=30}, Member{age=20}, Member{age=10}]

3.null 포함 nullLast

List<Member> list = List.of(Member.of(10), Member.of(null), Member.of(30));

List<Member> result = list.stream()
    .sorted(Comparator.comparing(Member::getAge, Comparator.nullsLast(Comparator.naturalOrder())))
    .collect(Collectors.toList());

System.out.println(result);

결과

[Member{age=10}, Member{age=30}, Member{age=null}]

4.null 포함 nullFirst

List<Member> list = List.of(Member.of(10), Member.of(null), Member.of(30));

List<Member> result = list.stream()
    .sorted(Comparator.comparing(Member::getAge, Comparator.nullsFirst(Comparator.naturalOrder())))
    .collect(Collectors.toList());

System.out.println(result);

결과

[Member{age=null}, Member{age=10}, Member{age=30}]

예제 Member class

class Member{

    Integer age;

    public Member(Integer age){
        this.age = age;
    }

    public static Member of(Integer age){
        return new Member(age);
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Member{" +
                "age=" + age +
                '}';
    }
}

+ Recent posts