Skip to content

Convert List to Map in Java Example (HashMap)

This example shows how to convert List to Map in Java using various ways including Java 8. The example also shows how to convert ArrayList or LinkedList to HashMap having duplicate elements.

How to convert List to Map in Java?

The List and Map are two different types of collections. The List is an ordered collection of the same type of elements while the Map maintains a mapping of a key to a value. There is no direct way to convert from one to another.

In the below given example, I will show you how to convert a List containing the objects of the Employee class to a HashMap object.

Output

As you can see from the output, the HashMap has the employee ID as the key and Employee object as the value.

Important Tip:

The HashMap class does not guarantee to maintain the insertion order of the mappings. If the order of the mappings is important for you, you can use the LinkedHashMap class instead of the HashMap class.

How to convert List to HashMap using the Java 8 stream?

If you are using Java version 8 or later, you can use the stream to convert List to Map as given below.

Output

This example is a part of the Java HashMap tutorial.

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

About the author

We are on YouTube!

Leave a Reply

Your email address will not be published.