Collections

Convert Map to List in Java example

Convert Map to List in Java example shows how to convert Map to List in Java. Example also shows how to convert HashMap to ArrayList or LinkedList containing values, keys or entries of the Map.

We are going to use Employee class for this example. Let’s first create a HashMap containing the Employee objects as given below.

HashMap contains Employee id as the keys and Employee objects as the values.

How to convert HashMap keys to List?

To get all the keys of HashMap use keySet method of HashMap class.

This method returns set view of keys of the HashMap. You can then create List from the keys of the HashMap using constructor of ArrayList or LinkedList which accepts Collection as an argument.

This constructor returns a List containing all the elements of the collection in the order they are returned from collection’s iterator.

Output

Note:

You may have observed from the output that the keys are not in the order they were inserted. That is because HashMap does not maintain insertion order of the elements.

How to convert HashMap values to List?

To get all the values stored in the HashMap, use values method of HashMap class.

This method returns Collection view of the values stored in the HashMap. You can then create List from the values of the HashMap using constructor of ArrayList or LinkedList which accepts Collection as an argument.

Output

Note:

You may have observed from the output that the values are not in the order they were inserted. That is because HashMap does not maintain insertion order of the elements.

How to convert HashMap entries to List?

To get all the entries stored in the HashMap, use entrySet method of HashMap.

This method returns Set view of the mappings (entries) stored in the HashMap. You can then create List from the Set containing HashMap entries using constructor of ArrayList or LinkedList which accepts Collection as an argument.

Output

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *