Convert Stream to a Map in Java 8

In this post, we will see how to convert Stream to a Map in Java.


 

1. Converting Stream of String[]

The Java 8 Stream API can be used to construct maps by obtaining stream from static factory methods like Stream.of() or Arrays.stream() and accumulating the elements of the stream into a new map using collectors.

We know that a Stream of String[] is essentially a sequence of items, not a sequence of key/value pairs. To extract a Map out of it, we can use Collectors.toMap() method where we provide proper mapping functions to specify how to extract keys and values from elements of the stream.

 

Download   Run Code

Output:

{CAR=Audi, BIKE=Harley Davidson}

 
To initialize a map with different types for key and value, we can do:

 
We could also adapt a Collector to perform an additional finishing transformation. For example, we could adapt the toMap() collector to always produce an immutable map with:

 

2. Converting Stream of Map.Entry to Map

Method references in Java 8 made it very easy to construct maps from stream of Map.Entry as shown below:

Download   Run Code

Output:

{CAR=Audi, BIKE=Harley Davidson}

 
As seen before, to get an immutable map we can do:

 
We can also use lambda expressions instead of method references.

 
Collectors class provides several overloaded versions of toMap() method –

 
1. For any duplicate keys present in the map, to avoid IllegalStateException, we can provide a merge function which is used to resolve collisions between values associated with the same key or we can create a multimap by using Collectors.groupingBy() as demonstrated here.

 
2. We can also specify the Type of the Map instance to be returned in another version of toMap() method as shown below:

 

3. Converting Stream of AbstractMap.SimpleEntry

 
Another approach which can easily accommodates different types for key and value involves creating a Stream of map entries. There are two implementations of Map.Entry Interface:

1. AbstractMap.SimpleEntry

 

Download   Run Code

Output:

{USA=Washington DC, UK=London}

 
2. AbstractMap.SimpleImmutableEntry

 

Download   Run Code

Output:

{USA=Washington DC, UK=London}

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz