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

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 *