map transforms all the elements stored in its stream object
map method uses two type variables
The Stream interface takes Stream <T>
and the map method returns Stream <R>
.
public interface Stream<T> ...
<R> Stream<R> map(Function<? super T,? extends R> mapper)
Declaring the Stream interface. Here, the type variable T is specified to make a generic type interface. That is, any type can be handled.
Defines the signature of the map method.
<R>
-> Declaration of type variable
-> The map method allows you to use two type variables, T and R.
Stream<R>
-> Declaration of return value of map method
-> The return value of the map method is Stream
** Since the map method is defined in the Stream \ <T > interface, this method will be responsible for converting Stream <T>
to Stream <R>
. ** **
map
-> Method name
Function<? super T, ? extends R>
-> Argument type
-> Function is a functional interface introduced from Java8
-> Function interface takes a T-type object and returns an R-type object
-> ? Super
and? Extends
are notations called boundary wildcards
-> This widens the range of functions that can be passed to the map method.
mapper
-> Formal argument name
sample.java
public List<String> collectEmpNames(List<Employee> employees) {
return employees.stream()
.map(e -> e.getName())
.collect(Collectors.toList());
}
The stream () method is called to convert the Employee List to Stream.
You are calling the map method. Extract the name from each element in the Stream of Employee and convert it to Stream of string.
e -> e.getName()
The map method takes a Function type function object as an argument.
The above lambda expression is an object that implements the Function interface.
Specifically ... Employee is stored in Stream when the map method is called. That is, the type T is Employee. Therefore, you can call getName () of the Employee class on the right side of the expression. Since the return value of getName () is String, the return value of the map method will be Stream \ <String >.
Calling the collect method to convert Stream to List.
Recommended Posts