Skip to content

Convert ArrayList to LinkedHashSet in Java Example

This example shows how to convert ArrayList to LinkedHashSet in Java. This example also shows how to convert ArrayList to LinkedHashSet using Java 8 Stream, addAll method, and constructor.

How to convert ArrayList to LinkedHashSet in Java?

There are several ways using which we can convert ArrayList to LinkedHashSet object as given below.

1. Using the LinkedHashSet constructor

The LinkedHashSet class provides a constructor that accepts a Collection object.

This constructor creates a new LinkedHashSet object containing all the elements of the specified collection object.

Output

2. Using the addAll method of the LinkedHashSet class

We can also create an empty LinkedHashSet object first and then add all elements of the ArrayList to it using the addAll method as given below.

Output

3. Using the Java 8 Stream

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

Output

Important Note:

As we can see from the output, the ArrayList object contained element “1” twice, while the converted linked hash set object contains the element “1” only once. That is because the LinkedHashSet class is an implementation of the Set interface that does not allow duplicate elements to be added to it.

How to convert ArrayList of custom class objects to LinkedHashSet?

Let’s try it first and see what happens.

Output

As we can see from the output when we converted ArrayList to LinkedHashSet it did not remove duplicate objects of the custom class. It is because the LinkedHashSet relies on the equals method of its elements to compare and check if the element already exists before adding it.

Since the User class has not overridden the equals method, the equals method inherited from the Object class is used for comparison which compares the object references, not the actual object contents. That is the reason the equals method returned false and the same element was added thrice.

Let’s override the equals and hashCode method in the User class and try again.

Output

This time duplicate elements were not added to the LinkedHashSet object.

This example is a part of the LinkedHashSet in Java Tutorial with Examples.

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

References:
Java 8 LinkedHashSet

About the author

Leave a Reply

Your email address will not be published.