How a lambda expression maps into a functional interface?

Supun Wijerathne :

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?

Eugene :

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);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=444974&siteId=1