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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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