728x90
반응형
[자바의 정석 - 기초편] 람다
람다식
- 함수(메서드)를 간단한 식으로 표현하는 방법
람다식 작성
1. 메서드의 이름과 반환타입 제거하고 '->'를 블록{} 앞에 추가
int max(int a, int b) { return a > b ? a : b; } |
-> | return a > b ? a : b; } |
2. 반환값이 있는 경우, 식이나 값만 적고 return문 생략 가능(끝에 ';' 안 붙임)
(int a, int b) -> { } |
-> | (int a, int b) -> a > b ? a : b |
3. 매개변수의 타입이 추론 가능하면 생략가능
( |
-> | (a, b) -> a > b ? a : b |
주의사항
1. 매개변수가 하나인 경우, 괄호() 생략가능(타입이 없을 때만)
(a) -> a * a (int a) -> a * a |
-> | a -> a * a // OK int a -> a * a // error |
2. 블록 안의 문장이 하나뿐 일 때, 괄호{} 생략가능(끝에 ';' 안 붙임)
(int i) -> { System.out.println(i) } | -> | (int i) -> System.out.println(i) |
람다식은 익명 함수? 익명 객체?
-람다식은 익명 객체
(a, b) -> a > b ? a : b | -> | new Object() { int max(int a, int b) { return a > b ? a : b; } } |
- 람다식(익명 객체)를 다루기 위한 참조변수가 필요. 참조변수의 타입은?
Object obj = new Object() {
int max(int a, int b) {
return a > b ? a : b;
}
};
타입 obj = a > b ? a : b; // obj는 참조변수, a > b ? a : b 는 객체
int value = obj.max(3, 5); // error! Object클래스에 max()가 없음
함수형 인터페이스
- 단, 하나의 추상 메서드만 선언된 인터페이스
@FunctionalInterface // 함수형 인터페이스는 단 하나의 추상 메서드만 가져야 함
interface MyFunction {
public abstract int max(int a, int b);
}
MyFunction f = new MyFunction() {
public int max(int a, int b) {
return a > b ? a : b;
} // 익명클래스, 클래스의 선언, 객체 생성 동시에
};
int value = f.max(3, 5);
- 함수형 인터페이스 타입의 참조변수로 람다식을 참조할 수 있음
MyFunction f = a > b ? a : b;
int value = f.max(3, 5);
함수형 인터페이스 example
- 익명 객체를 람다식으로 대체
@FunctionalInterface
interface Comparator<T> {
public int compare(T o1, T o2);
}
List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa");
Collections.sort(list, new Comparator<String>() {
public int compare(String s1, String s2) {
return s2.compareTo(s1);
}
});
↓
List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa");
Collections.sort(list, (s1, s2) -> s2.compareTo(s1));
함수형 인터페이스 타입의 매개변수, 반환타입
@FunctionalInterface
interface MyFunction {
void myMethod();
}
public class Test {
static void aMethod(MyFunction f) {
f.myMethod();
}
public static void main(String[] args) {
MyFunction f = () -> System.out.println("myMethod()");
aMethod(f);
}
}
메서드 참조
- 하나의 메서드만 호출하는 람다식은 '메서드 참조'로 더 간단히 할 수 있다.
종류 | 람다 | 메서드 참조 |
static 메서드 참조 | (x) -> ClassName.method(x) | ClassName::method |
인스턴스메서드 참조 | (obj, x) -> obj.method(x) | ClassName::method |
- static 메서드 참조
Integer method(String s) {
return Integer.parseInt(s);
}
int result = obj.method("123");
int result = Integer.parseInt("123");
↓
Function<String, Integer> f = (String s) -> Integer.parseInt(s);
↓
Function<String, Integer> f = Integer::parseInt;
System.out.println(f.apply("100")+200);
생성자의 메서드 참조
- 생성자와 메서드 참조
Supplier<MyClass> s = () -> new MyClass(); // 람다식
Supplier<MyClass> s = MyClass:new; // 메서드 참조
MyClass mc = s.get();
Function<Integer, MyClass> s = (i) -> new MyClass(i); // 람다식
Function<Integer, MyClass> s = MyClass::new; // 메서드 참조
MyClass mc = f.apply(100);
Function<Integer, int[]> f = x -> new int[x]; // 람다식
Function<Integer, int[]> f = int[]::new; // 메서드 참조
int[] arr = f.apply(100);
728x90
반응형
'개발 관련 강의 정리 > 자바의정석' 카테고리의 다른 글
[자바의 정석] 스트림 정리 (0) | 2023.07.10 |
---|---|
[자바의정석] 애너테이션 정리 (0) | 2023.04.19 |
댓글