jgwk
lambda (2) - method references 본문
jdk8 이 나오고 어느날 코드를 보다 이걸 봤을땐 당황했었다. 이 생소한 문법은 무엇인가.. 메서드 참조다.
람다를 하나의 표현식으로 구현하는 경우 메서드 참조로 대체할 수 있다. 람다 자체를 생략하고 쓸 수 있어 코드의 양이 줄어든다. 굳이 하는 마음이 조금 든다. 어쨋든 코드가 줄어드니 쓸꺼다.
메서드와 생성자도 호출이 가능하고, 첫번째 인자에 대한 임의 호출도 가능하다. 예제는 튜토리얼을 보고 가볍게 작성했는데, 실제 프로그래밍을 할때 편하게 쓰려면 익숙해지는 시간이 필요해 보인다.
사용 예를 첨부한다.
public class MethodReferences {
public static void main(String[] args) {
basic();
staticMethod();
instanceMethod();
constructor();
}
private static void basic() {
Consumer<String> c = System.out::println;
IntUnaryOperator o = Math::abs;
Function<Integer, String[]> f = String[]::new;
}
private static void staticMethod() {
String s = MethodReferences.merge("static", "Method", MethodReferences::merge1);
System.out.println(s);
}
private static void instanceMethod() {
MethodReferences mr = new MethodReferences();
String s = MethodReferences.merge("instance", "Method", mr::merge2);
System.out.println(s);
// with arbitrary object
String s2 = MethodReferences.merge("arbitrary", "Object", String::concat);
System.out.println(s2);
}
private static void constructor() {
Set<String> s = MethodReferences.make(HashSet::new);
}
public static <T, R extends Collection<T>> R make(Supplier<R> s) {
return s.get();
}
public static <T> T merge(T a, T b, BiFunction<T, T, T> f) {
return f.apply(a, b);
}
public static String merge1(String a, String b) {
return a + b;
}
public String merge2(String a, String b) {
return a + b;
}
}
참조
'java' 카테고리의 다른 글
spring profile or maven profile (0) | 2021.11.28 |
---|---|
stream (1) (0) | 2021.05.25 |
lambda (1) (0) | 2021.05.24 |
openjdk 설치 (mac, brew, adopt) (0) | 2021.04.13 |
eclipse 처음 설정 (0) | 2021.01.24 |
Comments