Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a lambda expression maps into a functional interface?

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?

like image 600
Supun Wijerathne Avatar asked Oct 16 '17 12:10

Supun Wijerathne


People also ask

How does a lambda expression related to a functional interface?

Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.

How is lambda expression related to functional interface in Java?

From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces.

Is functional interface mandatory for lambda expressions?

You do not have to create a functional interface in order to create lambda function. The interface allow you to create instance for future function invocation.

Is lambda expressions are always assigned to a functional interface in Java 8?

Lambda expressions are introduced in Java 8, and they can represent the instance of a functional interface.


2 Answers

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);
like image 85
Eugene Avatar answered Oct 13 '22 17:10

Eugene


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

like image 2
ByeBye Avatar answered Oct 13 '22 18:10

ByeBye