We have many ways to initialize HashSet in java.
HashSet can be initialized in one line, Using constructors, Using Arrays.
1. Initialize HashSet using Constructors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.kscodes.sampleproject; import java.util.HashSet; import java.util.Set; public class HashSetInitalize { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("Spring"); hashSet.add("Hibernate"); hashSet.add("JavaScript"); System.out.println(hashSet.toString()); } } |
2. Initialize HashSet in One line using Arrays.asList()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.kscodes.sampleproject; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class HashSetInitalize { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(Arrays.asList("Java", "JSP", "JavaScript", "JQuery")); System.out.println(hashSet.toString()); } } |
3. Initialize HashSet using Collections (Another List)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.kscodes.sampleproject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class HashSetInitalize { public static void main(String[] args) { List<String> arrList1 = new ArrayList<>(Arrays.asList("Java","JSP","JavaScript","JQuery")); Set<String> hashSet = new HashSet<>(arrList1); System.out.println(hashSet.toString()); } } |