Collections

Convert array to Set (HashSet) Example

Convert array to Set Example shows how to convert array to Set (HashSet) in Java. Example also shows how to convert array to Set (HashSet) using various approaches.

How to convert array to Set (HashSet)?

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

1) Convert array to Set (HashSet) using HashSet constructor

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

2) Convert array to Set (HashSet) using addAll method of HashSet

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

3) Convert array to Set (HashSet) using addAll method of Collections

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

4) Convert array to Set (HashSet) using for loop

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

5) Convert array to Set (HashSet) using Apache Commons

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

6) Convert array to Set (HashSet) using stream (Java 8)

If you are using Java 8, you can use stream to convert array to HashSet as given below.

7) Convert array to Set (HashSet) using toCollection method of Collectors (Java 8)

If you are using Java 8, you can use 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 “Java” element twice. HashSet does not allow duplicate elements and thus it was removed when array was converted to HashSet.

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.