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
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.
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.
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.
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());
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With