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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of