Java 8 Stream map With Examples

Java 8 Stream map function can be used to perform some operation on all of it’s elements. Java Stream map is an intermediate operation, so it returns Stream.

Java 8 Stream Map

Below is the map method declared in Java 8 Stream interface.

Stream map method takes Function as argument that is a functional interface.

Let’s now look at some example where stream map method become useful.

Java Stream map example

Let’s assume we have a list of names and we want to find which of them are present in some Oracle database table. Now since Oracle is case sensitive, we can convert list of string to upper case and then at the database side we can use to_upper method with SQL query.

Usually before java 8, we can do it using for loop as shown below.

We can do the same thing using java stream map function as shown below in a single line.

We can also write it like below.

Java Stream map example with objects

Now let’s look at more practical example of Stream map usage. We have an Emp class as below.

We have a method to get all the employees data. Now we want to pass employees data to HR system but we don’t want to disclose the salary. So we will have to use below code to process each employee and remove their salary.

Now using java 8 stream map function, we can do the same thing like below.

Below is the final program for java stream map example with object transformation.

When we run the above program, we get below output.

We can also convert the Emp object to some other object in the map method Function implementation.

That’s all for java 8 stream map examples.

Reference: Official JavaDoc

By admin

Leave a Reply

%d bloggers like this: