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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.kscodes.sampleproject; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ArrayListToHashSetExample { public static void main(String[] args) { List<String> arrayList1 = new ArrayList<>(); arrayList1.add("Java"); arrayList1.add("JSP"); arrayList1.add("JavaScript"); arrayList1.add("JQuery"); arrayList1.add("Spring MVC"); arrayList1.add("JQuery"); arrayList1.add("JSP"); System.out.println("Elements in ArrayList :: "+ arrayList1); System.out.println("Size of ArrayList :: "+ arrayList1.size()); //Convert to hashSet Set<String> hashSet1 = new HashSet<>(arrayList1); System.out.println("Elements in HashSet :: "+ hashSet1); System.out.println("Size of HashSet :: "+ hashSet1.size()); } } |
Output
1 2 3 4 |
Elements in ArrayList :: [Java, JSP, JavaScript, JQuery, Spring MVC, JQuery, JSP] Size of ArrayList :: 7 Elements in HashSet :: [JSP, JQuery, Spring MVC, JavaScript, Java] Size of HashSet :: 5 |
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.