Convert Map to a List in Java 8

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


 

1. Convert Map to List<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 List of key-value pairs by converting it to stream as shown below:

Download   Run Code

Output:

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

Here’s even shorter version of above code that make use of ArrayList constructor to create a list of Map.Entry<K,V> objects containing both key and value:

Download   Run Code

 

2. Convert Map to List<K>

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

Download   Run Code

Output:

[A, B, C]

Here’s better way to do in Java 8 using Map.keySet():

Download   Run Code

 

3. Convert Map to List<V>

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

Download   Run Code

Output:

[65, 66, 67]

Here’s better way to do in Java 8 using Map.values():

Download   Run Code

 
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