How to convert ArrayList to HashSet

In this post we will see examples to convert ArrayList to HashSet in java.
HashSet and ArrayList are both Collection objects. Hence we can pass ArrayList to the construtor of the HashSet and get it converted.

Please note that HashSet doesn’t allow duplicate values, so any duplicate values that are present in the ArrayList will be eliminated while conversion.

Example : Convert ArrayList to HashSet

Output

Points to Remember

1. As you can see in the above example the ArrayList has 7 elements, but few elements were duplicate.
When we converted ArrayList to HashSet, the total size went down to 5, removing the duplicate elements.

2. Also when we print the HashSet, the order of elements are not guaranteed, unlike ArrayList/List HashSet doesn’t preserve the order of the elements. For that you may need to use a LinkedHashSet.

Reference

1. ArrayList

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn