Convert ArrayList to LinkedHashMap in Java Example

This example shows how to convert an ArrayList to LinkedHashMap in Java. The example also shows how to convert ArrayList to LinkedHashMap using Java 8 stream.

How to convert ArrayList to LinkedHashMap in Java?

The ArrayList and LinkedHashMap are two different data structures. The ArrayList is a resizable array implementation of the List interface while the LinkedHashMap is an implementation of the Map interface that maps keys to values.

Suppose you have an ArrayList containing the objects of the Student class that you want to convert to a LinkedHashMap. The LinkedHashMap maps keys to corresponding values. In this case, you can use the student id as a key and the Student object as the value of the LinkedHashMap.

Output

How to convert to LinkedHashMap using Java 8?

If you are using Java version 8 or above, you can use the stream to convert to a LinkedHashMap object as given below.

Output

Important Note:

In the above examples, I used the Student class that has id as a unique field so it was used as the LinkedHashMap key. Before converting, identify the unique field in your class and use it as the key of the map object.

Since the LinkedHashMap class maps a key to a value and cannot have duplicate keys, If the ArrayList has duplicate elements, the converted LinkedHashMap will contain only one entry for the given duplicated key.

This example is a part of the LinkedHashMap in Java Tutorial.

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

References:
Java 8 LinkedHashMap

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 *