Convert ArrayList to HashSet in Java Example

This example shows how to convert ArrayList to HashSet in Java. The example also shows how to convert using the HashSet constructor, addAll method, and Java 8 stream.

How to convert an ArrayList to HashSet in Java?

There are several ways using which you can convert an ArrayList object to the HashSet object in Java as given below.

1. Using the addAll method

The addAll method of the HashSet class adds all elements of the specified collection to this set object.

It returns true if this set is changed as a result of the method call, false otherwise.

Output

Tip: Use this approach when you already have an existing empty object of the HashSet class.

2. Using the constructor

We can also use the HashSet constructor that accepts Collection as an argument.

This constructor creates a new HashSet object having the elements contained in the specified collection object.

Output

Tip: Use this approach when you do not have an existing HashSet object.

3. Using the stream (Java 8)

We can also use the Java stream to convert List to Set as given below.

Output

Important Note: As we can see from all the outputs, only unique elements from the ArrayList are added to the HashSet object.

Converting ArrayList of custom objects to a HashSet object

The HashSet class relies on the equals method to prevent duplicate elements from being added to it. When we convert an ArrayList containing duplicate objects of a custom class, and if the custom class has not implemented the equals and hashCode methods, duplicate objects will be added to the HashSet too.

Output

To solve this duplication problem, we need to implement the equals and hashCode method in our custom class as given below.

Output

As we can see from the output, now only unique custom class objects are added to the HashSet.

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

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

References:
Java 8 HashSet

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 *

Online Shopping