This post will discuss how to convert a stream to a map in Java.

1. Converting Stream of String[]

We can use the Java 8 Stream to construct maps by obtaining stream from static factory methods like Stream.of() or Arrays.stream() and accumulating the stream elements 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 the Collectors.toMap() method, where we provide proper mapping functions to specify how to extract keys and values from stream elements.

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 and above made it very easy to construct maps from a 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 the toMap() method:

 
1. For any duplicate keys present on 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 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 the toMap() method, as shown below:

3. Converting stream of AbstractMap.SimpleEntry

 
Another approach that can easily accommodate different types for key and value involves creating a stream of map entries. There are two implementations of the Map.Entry interface:

1. Using AbstractMap.SimpleEntry<K,V>:

Download  Run Code

Output:

{USA=Washington DC, UK=London}

 
2. Using AbstractMap.SimpleImmutableEntry<K,V>:

Download  Run Code

Output:

{USA=Washington DC, UK=London}

That’s all about converting Stream to a Map in Java.