Convert Map to a Stream in Java

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


 

1. Convert Map to Stream<Map.Entry<K,V>>

We know that Map.entrySet() returns a Set view of the mappings contained in this map. In Java 8, we can easily get a Stream of key-value pairs as shown below:

Download   Run Code

Output:

[A=65, B=66, C=67]

 

2. Convert Map to Stream<K>

We can get a Stream of keys of the Map using Map.keySet() in Java 8:

Download   Run Code

Output:

[A, B, C]

 

3. Convert Map to Stream<V>

We can get a Stream of values of the Map using Map.values() in Java 8:

Download   Run Code

Output:

[65, 66, 67]

 
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