1. @FunctionalInterface
사용자 정의 인터페이스
@FunctionalInterface
interface Plus {
void plus(int a, int b, int c);
}
Plus pl = (a, b, c) -> System.out.println("1. FuctionalInterface: " + (a + b + c));
pl.plus(1, 2, 3);
인터페이스를 사용해서 람다 객체를 생성할 때 인터페이스를 직접 정의하지 않고도,
자바에서 제공하는 인터페이스를 사용해서 람다 객체를 생성할 수 있다.
2. Consumer<T> : 리턴값이 없는 accept() 메서드
Consumer<String> consumer = (t) -> System.out.println(t);
consumer.accept("2. Hello Consumer");
3. Supplier<T> : 매개변수가 없고, 리턴값이 있는 get() 메서드
Supplier<String> supplier = () -> {
String str = "3. Hello Supplier";
return str;
};
String str = supplier.get();
System.out.println(str);
4. Function<T, R> : 매개변수가 있고, 리턴값이 있는 apply() 메서드 (R은 리턴타입)
Function<String, String> function = (s) -> {
switch(s) {
case "ko": return "4. 안녕하세요. Function";
case "en": return "4. Hello! Function";
}
return "기본값";
};
String msg = function.apply("ko");
System.out.println(msg);
// .andThen을 활용하려면 function의 리턴 타입이 function2의 매개변수 타입과 동일해야함
Function<String, String> function2 = (s) -> {
switch(s) {
case "4. 안녕하세요. Function": return s + " - 한글";
case "4. Hello! Function": return s + " - 영어";
}
return "기본값";
};
String msg2 = function.andThen(function2).apply("ko");
System.out.println(msg2);
5. Operator : 매개변수가 있고, 리턴값이 있는 apply() 메서드
- BinaryOperator<T> : 매개변수 2개, 리턴값 1개
- UnaryOperator<T> : 매개변수 1개, 리턴값 1개
BinaryOperator<String> operator = (a, b) -> {
switch(a) {
case "ko": return "5. 안녕하세요. Operator! " + b;
case "en": return "5. Hello! Operator!" + b;
}
return "기본값" + b;
};
String msg3 = operator.apply("ko", "홍길동");
System.out.println(msg3);
6. Predicate<T> : 리턴값이 논리값을 제공하는 test() 메서드
Predicate<Integer> pred = (a) -> {
return a > 10;
};
String msg4 = pred.test(11)?"10보다 큰 수입니다.":"10보다 작은 수 입니다.";
System.out.println(msg4);
728x90
'Java' 카테고리의 다른 글
[Java] Upcasting (업캐스팅) (0) | 2024.10.31 |
---|---|
[Java] Stream (0) | 2024.10.23 |
[Java] Set 인터페이스와 Map 인터페이스 (0) | 2024.10.21 |
[Java] Link 인터페이스를 구현한 ArrayList와 LinkedList (0) | 2024.10.21 |
[Java] 실수 float, double (0) | 2024.10.18 |