Lambda Expression은 메소드를 하나의 식(expresson)으로 표현할 수 있도록 하여, 함수를 간결하고 명확한 식으로 표현할 수 있게 해주는 Java의 함수형 언어 지원입니다.
@FunctionalInterface
public interface BinaryOp {
int apply(int x, int j);
}
class Algo {
public static int calc(BinaryOp binder, int i, int j) {
return binder.apply(i, j);
}
}
class Test {
public static void main(String[] args) {
BinaryOp adder = (x, y) -> x + y;
Algo.calc(adder , 1, 2);
Algo.calc((x, y) -> x * y, 1, 2);
}
}
Anonymous Method 형식으로 동작하는 Lambda Expression은 파라미터를 받아 짧은 코드 블록으로 수행하고 필요에 따라 값을 반환하는 표현 방법을 말합니다.
하나의 abstract method를 가지고 있는 인터페이스
-- SAM(Single Abstract Method) 인터페이스
@FunctionalInterface 어노테이션이 적용될 수 있는 Target 인터페이스
Java에서 함수를 객체처럼 다를 수 있도록 함
Funcational Interface의 자격은 단 하나의 abstract method를 가지는데 한합니다. static 메소드와 default 메소드의 존재는 인터페이스가 Funcational Interface로 취급되는데 영향을 미치지 않습니다.
@FunctionalInterface
public interface RunSomething {
void doIt();
static void printName(){
System.out.println("catsbi");
}
default void printAge(){
System.out.println("33");
}
}
Functional Interface는 Java에서 함수를 객체처럼 다룰 수 있도록 합니다.
@FunctionalInterface
public interface BinaryOp {
public int apply(int right, int left);
}
BinaryOp binder = new BinaryOp() {
public int apply(int right, int left) {
return right + left;
}
};
@FunctionalInterface
public interface RunSomething {
void doIt();
static void printName(){
System.out.println("catsbi");
}
default void printAge(){
System.out.println("33");
}
}
RunSomething run = () -> System.out.println("Hello, World!");
RunSomething run2 = () -> {
System.out.print("Hello,");
System.out.println(" World!");
};
(int a) -> { return a + a; }
(int a, int b) -> { int temp = a * b; System.out.println(temp); }
() -> { System.out.println(“Hello World!”); return 0; }
(a, b) -> { return a + b; }
(x) -> { return x * x * x; }
a -> { int x = a + b; … }
x -> return x * x * x: // 사용 불가
x -> { return x * x * x: } // 사용 가능
x -> x * x * x () -> Math.random()
x -> x
public interface BinaryOp {
public int apply(int i, int j);
}
class Calc {
public static int add(int i, int j) {
return i + j;
}
public int mult(int i, int j) {
return i * j;
}
}
class Test {
public static void main(String[] args) {
BinaryOp adder = Calc::add;
BinaryOp multer = new Calc()::mult;
System.out.println(adder.apply(1, 2));
System.out.println(multer.apply(2, 3));
}
}