학습 내용/책 내용 및 회고

모던 자바 인 액션 - 2022-3-24

ohksj77 2022. 3. 27. 16:50
public class Apple {
    private Integer weight;
    public Integer getWeight(){
        return weight;
    }
}

이러한 weight를 가지는 Apple이라는 클래스가 있다.

public class Main {
    private static List<Apple> inventory = new ArrayList<>();
    public static void main(String[] args) {
        Collections.sort(inventory, new Comparator<Apple>(){
            public int compare(Apple a1, Apple a2){
                return a1.getWeight().compareTo(a2.getWeight());
            }
        });
    }
}

Apple 클래스에서 weight를 비교해주는 코드이다.

이 Main클래스를 다음과 같이 바꿀 수 있다.

public class Main {
    private static final List<Apple> inventory = new ArrayList<>();
    public static void main(String[] args) {
        inventory.sort(comparing(Apple::getWeight));
    }
}

훨씬 간단한 한 줄로 변환되었지만 같은 기능을 수행하는 코드이다.