Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression java 8 map method

Tags:

lambda

java-8

The syntax of map method in java 8 is :

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

but i can use a lambda expression :

personList.stream().filter(p -> p.getPersonType().equals("student"))
            .map(p -> new Student(p.getId(), p.getName()))
            .collect(Collectors.toList());

How does the argument in map method equates to a Function datatype.Please help me understand this .

Thanks

like image 586
jayendra bhatt Avatar asked Jun 13 '18 11:06

jayendra bhatt


People also ask

What is map in lambda expression Java?

Map is a function defined in java. util. stream. Streams class, which is used to transform each element of the stream by applying a function to each element.

What is the purpose of map () method of Stream in Java 8?

Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another.

What does map () do in Java?

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.


1 Answers

The function Function<? super T,? extends R> mapper of the map method basically represents any function taking one parameter and returning a value so in this specific case the lambda p -> new Student(p.getId(), p.getName()) is a function taking a Person p and returning a Student hence fits into that perfectly.

To look at it another way, the lambda is equivalent to:

.map(new Function<Person, Student>() {
     @Override
      public Student apply(Person p) {
            return new Student(p.getId(), p.getName());
      }
})
like image 75
Ousmane D. Avatar answered Oct 26 '22 17:10

Ousmane D.