Java 8 Stream map() examples

Java 8 Stream map()
Java 8 Stream map()

Java 8 Stream map()examples:-

In this article, we are going to check some Java 8 Stream map() examples. We create a map of the user and try to do some basic operations using the Java 8 Stream map() api.Java 8 stream api has a lot of other api’s as well which is of great use.

Create a User Bean:-

We are creating a bean with some basic getters and setter.

Create a Map Of users:-

Iterate Map and Show Values:-


In Java 8 collections we can use expressions inside parenthesis bracket and pass parameters.In the second list of our Java 8 Stream map() example, we are iterating using Keys of the map and iterating values and store map into a list.

Convert Map to List:-


We are using a filter to filter the map and put values in the List.As you notice we have filtered the list map element with an id greater than 1 from our hashmap.We are getting an output as 2,3 because we have printed list of keys.

Convert List To a Map:-

We are going to create a list of Users and will try and convert the list to a map.



Modify A Map:-

There are various methods present in java to modify a map using put, contains and other methods.

Let’s say we are having following map and we want to modify the map only if any key is found or already present . let’s see how we will do in prior to Java 8.

Update Map if key is Present:-

Let’s first look at the old way using put and containsKeywith the following map.

Let’s see how we are going to do using Java 8 stream map

Update A Map if No Key Is Present :-

 Let’s first look at the old way using put and containsKeywith the following map.

Let’s see how we are going to do using Java 8 stream map.

Both the ways that we have demonstrated are most commonly used stream api methods and operations in a typical Java code base.We see how this declarative way makes our code concise and readable.

If we use puteIfAbsent a value null will be returned if the key-value mapping is successfully added to the hashmap object while if the id is already present on the hashmap the value which is already existing will return instead.

Go ahead and find out how can you replace your current code and use some Java 8 Stram map().

Since putIfAbsent takes a value  and  put in the map directly, it doesn’t provide any laziness. If you want a bit more laziness better use computeIfAbsent.

Please Feel free to Put Your comments and let me know What do you think about this Post and What posts do you Want? Contact me anytime Here.










Please enter your comment!
Please enter your name here