Stream<Y>. For each object of type
X, a new object of type
Y is created and put in the new
1. Stream map() API
1.1. Method Syntax
map() method has the following syntax.
<R> Stream<R> map(Function<? super T,? extends R> mapper)
Rrepresents the element type of the new stream.
mapperis a non-interfering, stateless function to apply to each element which produces a stream of new values.
- The method returns a new stream of objects of type
Stream interface has three more similar methods which produce
DoubleStream respectively after the map operation.
If the streams created after
map() operations are given return types then consider using these functions directly.
IntStream mapToInt(ToIntFunction<? super T> mapper) LongStream mapToLong(ToLongFunction<? super T> mapper) DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
map()is an intermediate operation. It returns a new
Streamas return value.
map()operation takes a
Function, which is called for each value in the input stream and produces one result value sent to the output stream.
- The mapper function used for transformation is a stateless function (does not store the information of previously processed objects) and returns only a single value.
map()method is used when we want to convert a Stream of
Xto Stream of
- The mapped stream is closed after its contents have been placed into the new output stream.
map()operation does not flatten the stream as
2. Stream map() Example
Example 1: Converting a Stream of Strings to a Stream of Integers
In this example, we will convert a
Stream<Integer>. Here the mapper function
Integer::valueOf() takes one string from the Stream at a time, and convert the
String to an
It then put the
Integer into another stream which is then collected using
List<String> listOfStrings = Arrays.asList("1", "2", "3", "4", "5"); List<Integer> listOfIntegers = listOfStrings.stream() .map(Integer::valueOf) .collect(Collectors.toList()); System.out.println(listOfIntegers);
[1, 2, 3, 4, 5]
Example 2: Finding all distinct salaries among all employees
Java example to find all possible distinct salaries for a
List of employees.
List<Employee> employeesList = Arrays.asList( new Employee(1, "Alex", 100), new Employee(2, "Brian", 100), new Employee(3, "Charles", 200), new Employee(4, "David", 200), new Employee(5, "Edward", 300), new Employee(6, "Frank", 300) ); List<Double> distinctSalaries = employeesList.stream() .map( e -> e.getSalary() ) .distinct() .collect(Collectors.toList()); System.out.println(distinctSalaries);
[100.0, 200.0, 300.0]
Drop me your questions related to Stream map() method in Java Stream API.
Happy Learning !!