Skip to content

Convert Map to List in Java example

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

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

The 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 the HashMap, use the keySet method of HashMap class.

This method returns a Set view of the keys of the HashMap. You can then create a List from the keys of the HashMap using the 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 the insertion order of the elements.

How to convert HashMap values to List?

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

This method returns Collection view of the values stored in the HashMap. You can then create a List from the values of the HashMap using the 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 the 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 a List from the Set containing HashMap entries using the constructor of ArrayList or LinkedList which accepts Collection as an argument.

Output

This example is a part of the Java HashMap tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.