Java 8 Stream Map

Previous
Next

In this post, we will see about Java 8 Stream map function.

Stream’s map method takes single element from input stream and produces single element to output stream. Type of Single input Stream and Output stream can differ.

Java 8 Stream Map function

Map function returns a stream consisting of the results of applying the given function to the elements of this stream.
Function is a functional interface available in Java 8 java.util.function.Function accepts one input and produce a result.
Let’s understand with the help of a simple example.

Java 8 Stream Map example

Let’s say you have a list of employees, now you want to convert it to list of employee names, so you will map each employee object to employee name.

Java 8 Stream map

You will give input as Stream of employee objects and get an output as Stream of String.

1. Create a class named “Employee.java”

2. Create main class named “Java8StreamMapMain.java”

When you run above program, you will get below output:

John
Martin
Mary
Steve

You can use method reference to at line no.17 as below

Another example

Let’s say you have list of integers and you want to find sum of double of even numbers.

When you run above program, you will get below output:

60

If you notice, we have used map function to double of input number in above example.

That’s all about Java 8 Stream map example.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog