Java에는 함수형 프로그래밍을 지원하는 다양한 인터페이스가 있다.
대표적인 몇 가지를 직접 만들어보자.
package ex07.ch02;
/*
1. Consumer
2. Supplier
3. Predicate (true or false) 논리, 예측
4. Function
5. Callable
*/
// 소비하는 친구
interface Con01 {
void accept(int n);
}
// 공급하는 친구
interface Sup01 {
int get(); // 리턴이 있어야 함.
}
// 예견하는 친구
interface Pre01 {
boolean test(int n); // boolean 리턴이 있어야 함.
}
// 함수
interface Fun01 {
int apply(int n1, int n2);
}
// 기본
interface Cal01 {
void call(); //
}
// 절대 만들지 마라 !! 써먹기만 하면 된다 !!
public class Beh02 {
public static void main(String[] args) {
// 1. Consumer
Con01 c1 = (n) -> {
System.out.println("소비 : " + n);
};
c1.accept(10);
// 2. Supplier
Sup01 s1 = () -> 1; // 중괄호를 안 쓰면 자동으로 return 코드가 된다.
int r1 = s1.get();
System.out.println("공급 받음 : " + r1);
// 3. Predicate
Pre01 p1 = (n) -> n % 2 == 0;
Pre01 p2 = (n) -> n % 3 == 0;
System.out.println("예측함 : " + p1.test(5));
System.out.println("예측함 : " + p2.test(6));
// 4. Function
Fun01 add = (n1, n2) -> n1 + n2;
Fun01 sub = (n1, n2) -> n1 - n2;
Fun01 mul = (n1, n2) -> n1 * n2;
Fun01 div = (n1, n2) -> n1 / n2;
System.out.println("함수 : " + add.apply(1, 2));
System.out.println("함수 : " + sub.apply(3, 4));
System.out.println("함수 : " + mul.apply(5, 6));
System.out.println("함수 : " + div.apply(7, 8));
// 5. Callable
Cal01 ca01 = () -> {
System.out.println("기본 함수");
};
ca01.call();
}
}
Share article