this
키워드는 바깥 인스턴스를 가리키기에 함수 객체 자신을 참조해야 한다면 익명클래스를 써야 한다.public static void main(String[] args) {
List<String> strings = Arrays.asList("book", "apple", "fineapple", "grape", "car", "bobo", "bbibbi", "crong");
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
});
}
익명 클래스를 사용해 문자열 정렬을 구현했다. 예전에는 이런 방식을 사용해 정렬을 구현했는데, Comparator
처럼 추상 메서드가 하나뿐인 인터페이스는 FunctionalInterface
라 하며 람다식을 사용할 수 있도록 해준다.
Collections.sort(strings, (s1, s2)-> Integer.compare(s1.length(), s2.length()));
s1, s2가 무슨 타입인지 따로 명시해주지 않았다.