Skip to content

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)

메서드 참조 쉽게 사용하는 방법

  1. 람다로 작성
  2. 그 람다 식을 메서드화
  3. 람다를 새로운 메서드로 대체

보통의 경우엔 메서드 람다보다 메서드 참조가 간결하지만 예외가 있다

GoshThisClassNameIsHumongous class 내부에 아래의 코드가 있다고 생각해보자

service.execute(GoshThisClassNameIsHumongous::action)

이를 람다로 대체하면?

service.execute(() -> action)

메서드와 람다가 같은 클래스에 있을 경우엔 람다가 더 짧고 명확할 수 있다.

메서드 참조의 5가지 유형

  1. 정적 메서드 참조(가장 많이 사용)
Integer::parseInt
str -> Integer.parseInt(str)
  1. 한정적 (인스턴스) 메서드 참조
Instant.now()::isAfter
Instance then = Instant.now(); t -> then.isAfter(t)
  1. 비한정적 (인스턴스) 메서드 참조
String::toLowerCase
str -> str.toLowerCase
  1. 클래스 생성자
TreeMap<K,V>::New
() -> new TreeMap<K,V>()
  1. 배열 생성자
int[]::new
len -> new int[len]

결론

메서드 참조 쪽이 짧고 명확하다면 메서드 참조를, 그렇지 않으면 람다를 사용하라

Clone this wiki locally