10

Let's look at the below code.

    List<String> names = Arrays.asList("Adam", "Brian", "Supun");
    List<Integer> lengths = names.stream()
                                 .map(name -> name.length())
                                 .collect(Collectors.toList());

And simply then will look at the javadoc for streams.map. There the signature for map method appears like this.

<R> Stream<R> map(Function<? super T,? extends R> mapper)

Can somebody please explain how JVM maps the lambda expression we gave (name -> name.length()) in terms of Function<? super T,? extends R> mapper?

3
  • 2
    What are you trying to accomplish? You shouldn't ever need to create local variables of the Stream type. Are you looking for names.stream().map(...).collect(Collectors.toList()) ? Also, don't use the raw List type. Commented Oct 16, 2017 at 12:53
  • @Michael actually I needed the viewers to focus on the lambda expression part. SO I didn't add the latter additions you have mentioned. This is just to understand the mapping of lambda into a functional interface. Nothing else. :)) Commented Oct 16, 2017 at 12:57
  • 1
    @Michael got your point. Thank You. :)) Hope I have corrected the code. Commented Oct 16, 2017 at 13:05

2 Answers 2

9

A Function is something that takes X and returns Y.

 ? super T     == String
 ? extends R   == Integer

basically with name -> name.length() you are implementing the @FunctionlInterface Function<T,R> with overriding the single abstract method R apply(T t).

You can also shorten that with a method reference :

Stream<Integer> lengths = names.stream().map(String::length);
Sign up to request clarification or add additional context in comments.

Comments

2

Check apply method from Function:

R apply(T t);

? extends R is return type, ? super T is taken type

As Function class has only one non-default public method, it can map your lambda to Function instance

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.