Skip to content

Convert array to Set (HashSet) Example

Convert array to Set Example shows how to convert array to Set (HashSet) in Java using various approaches including addAll method, constructor, Java 8 stream, and apache commons.

How to convert array to Set (HashSet)?

There are several ways using which you can convert array to Set (HashSet) as given below.

1) Using the HashSet constructor

You can first convert an array to List using the asList method of the Arrays class and then use the constructor of the HashSet class which accepts another collection parameter as given below.

2) Using the addAll method of HashSet

You can first convert an array to List using the  asList method of the Arrays class and then add all the elements of the List to HashSet using the addAll method of the HashSet as given below.

3) Using the addAll method of Collections

Alternatively, you can use the addAll method of the Collections class as well to add all the elements of an array to the HashSet as given below.

4) Using for loop

Loop through an array and add all the elements of an array to the HashSet one by one as given below.

5) Using Apache Commons

If you are using the Apache Commons library, you can use the addAll method of the CollectionUtils class to add all the elements of an array to HashSet as given below.

6) Using stream (Java 8)

If you are using Java 8, you can use a stream as given below.

7) Using the toCollection method of Collectors (Java 8)

If you are using Java 8, you can use the toCollection method and stream as given below.

 

Output

Note:

We had 5 elements in the array but when we converted an array to HashSet, only 4 elements were added. What happened to the missing one element? If you look carefully, array contained the “Java” element twice. The HashSet class does not allow duplicate elements and thus it was removed when the array was converted to the HashSet.

This example is a part of the Java Array tutorial and Java HashSet tutorial.

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

About the author

Leave a Reply

Your email address will not be published.