-
Notifications
You must be signed in to change notification settings - Fork 1
item 43 JungHyunLyoo
JungHyunLyoo edited this page Apr 25, 2020
·
2 revisions
익명 클래스 < 람다 < 메서드 참조(method reference)
람다 : map.merge(key, 1, (count, incr) -> count + incr)
메서드 참조 : map.merge(key, 1, Integer::sum)
- 람다로 작성
- 그 람다 식을 메서드화
- 람다를 새로운 메서드로 대체
GoshThisClassNameIsHumongous class 내부에 아래의 코드가 있다고 생각해보자
service.execute(GoshThisClassNameIsHumongous::action)
이를 람다로 대체하면?
service.execute(() -> action)
메서드와 람다가 같은 클래스에 있을 경우엔 람다가 더 짧고 명확할 수 있다.
- 정적 메서드 참조(가장 많이 사용)
Integer::parseInt
str -> Integer.parseInt(str)
- 한정적 (인스턴스) 메서드 참조
Instant.now()::isAfter
Instance then = Instant.now(); t -> then.isAfter(t)
- 비한정적 (인스턴스) 메서드 참조
String::toLowerCase
str -> str.toLowerCase
- 클래스 생성자
TreeMap<K,V>::New
() -> new TreeMap<K,V>()
- 배열 생성자
int[]::new
len -> new int[len]
메서드 참조 쪽이 짧고 명확하다면 메서드 참조를, 그렇지 않으면 람다를 사용하라