2019년 12월 5일 목요일

Java 8 Lambda Map 함수 사용 관련

람다 Map 함수를 사용하는 것에 관해서는 여기저기 잘 나와 있는데,
파라미터를 쓰지 않는 표현법을, 우리 팀 시니어 엔지니어가 자주 활용하길래.
물어본적이 있다.


이런 식인데, 아는 사람은 잘 알겠지만, 나는 아직 자바에 익숙치 않아서 찾아보았다.

https://javarevisited.blogspot.com/2014/02/10-example-of-lambda-expressions-in-java8.html

링크를 찾아가서 보면, 아래 쯤에 이런 문구가 있다.


---------------------
2) You can use method reference inside lambda expression if method is not modifying the parameter supplied by lambda expression. For example following lambda expression can be replaced with a method reference since it is just a single method call with the same parameter:


list.forEach(n -> System.out.println(n)); 


list.forEach(System.out::println);  // using method reference

However, if there’s any transformations going on with the argument, we can’t use method references and have to type the full lambda expression out, as shown in below code :


list.forEach((String s) -> System.out.println("*" + s + "*"));

You can actually omit the type declaration of lambda parameter here, compiler is capable to infer it from generic type of List.

----------------------------------
대충 해석해보면,

해당 메소드가 람다 표현식에서 제공하는 파라미터를 변경하지 않는다면, 이런 경우에 한해 람타 표현식 내에 그 메소드의 reference를 사용하는 것이 가능하다. 
예를 들어 이러한 람다식이 있을 때:

list.forEach(n -> System.out.println(n)); 


이것을 다음과 같이 표현하는 게 가능하다는 것이다:


list.forEach(System.out::println);  // using method reference

그렇지만, 그 아규먼트를 가지고 뭔가 변형시키는 부분이 있다면, 
이러한 메소드 레퍼런스 방식은 사용할 수 없고 다음과 같이 전체 표현식을 써야 한다.

list.forEach((String s) -> System.out.println("*" + s + "*"));

댓글 없음:

댓글 쓰기

아마존 7주년, 그리고 퇴사

밑에 보니 아마존 6주년 포스트가 있네. 그 포스트 후 다시 1년 반의 시간이 지남. 시간은 왜 이렇게 빨리 흐르는거야. 지금은 2026년 8월. 2026년 2월말이 아마존 근무 7주년이 되던 때이고, 4월달에 퇴사를 했다. 7년 1개월 정도만에 ...