[Effective Java 3/e] 아이템 42 - 익명 클래스보다는 람다를 사용하라


아이템 42 - 익명 클래스보다는 람다를 사용하라

익명 클래스의 인스턴스를 함수 객체로 사용 - 낡은 기법이다

Collections.sort(words, new Comparator<String>() {
  public int compare(String s1, String s2) {
    return Integer.compare(s1.length(), s2.length());
  }
})

람다식을 함수 객체로 사용 - 익명 클래스 대체

Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length()));

// 비교자 생성 메서드 사용
Collections.sort(words, comparingInt(String::length));

// 자바8 List 인터페이스의 sort 메서드 사용
word.sort(comparingInt(String::length));

정리

  • 익명 클래스는(함수형 이터페이스가 아닌) 타입의 인스턴스를 만들 때만 사용하라.