익명 클래스
익명 클래스의 인스턴스
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
System.out.println(words);
Collections.sort(words, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
System.out.println(words);
}
}
함수형 인터페이스
함수형 인터페이스의 인스턴스 == 람다(식)
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
System.out.println(words);
// 1.
Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length()));
// 2.
Collections.sort(words, comparingInt(String::length));
// 3.
words.sort(comparingInt(String::length));
System.out.println(words);
}
}
익명 클래스 인스턴스에서 this는 익명 클래스 인스턴스 자체를 가리킴.
람다에서 this는 바깥 인스턴스를 가리킨다.
함수 객체(람다)를 인스턴스 필드에 저장해 상수별 동작을 구현한 열거 타입
// 코드 42-4 함수 객체(람다)를 인스턴스 필드에 저장해 상수별 동작을 구현한 열거 타입 (256-257쪽)
public enum Operation {
PLUS ("+", (x, y) -> x + y),
MINUS ("-", (x, y) -> x - y),
TIMES ("*", (x, y) -> x * y),
DIVIDE("/", (x, y) -> x / y);
private final String symbol;
private final DoubleBinaryOperator op;
Operation(String symbol, DoubleBinaryOperator op) {
this.symbol = symbol;
this.op = op;
}
@Override public String toString() { return symbol; }
public double apply(double x, double y) {
return op.applyAsDouble(x, y);
}
// 아이템 34의 메인 메서드 (215쪽)
public static void main(String[] args) {
double x = 10;
double y = 5;
for (Operation op : Operation.values())
System.out.printf("%f %s %f = %f%n",
x, op, y, op.apply(x, y));
}
}