How to initialize a HashSet from an Array or a Collection in Java ?
Initialize hashset with values java: This article will give an clear idea about ho initialize a HashSet using a Array or a Collection. So let’s start the topic.
Java HashSet class has a constructor which receives a Collection as an argument and initializes the new Set with the elements of passed collection object. It contains unique elements only and stores data in a hash table using hashing mechanism.
public HashSet(Collection<? extends E> c)
Important :-
- It inherits
AbstractSet class
- Implements
Set interface
- Duplicate values not allowed
- But NULL elements are allowed
- Also implements
Serializable
andCloneable interfaces
Declaration of HashSet:
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Where,
- HashSet extends Abstract Set<E>
- HashSet implements Set<E>, Cloneable and Serializable interface
- ‘E’ refers to types of elements which is maintained by the set.
We can do this by two ways i.e
Initializing a HashSet with an array :
As we know array is not a Collection, hence it is required to first convert this array into a List
If we have an array like
String[] Arr = {"Goa", "Puri", "Kochi", "Ranchi"};
It will be converted into list like this
List<String> arrList = Arrays.asList(Arr);
Below code represents an example to initialize HashSet with String array
// Program : import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; public class Main { public static void main(String args[]) { // This is an array of String Objects String[] newArr = {"Goa", "Puri", "Kochi", "Ranchi"}; // A new Set from an array is created HashSet<String> newSet = new HashSet<>(Arrays.asList(newArr)); System.out.println(newSet); } }
Output : ["Goa", "Puri", "Kochi", "Ranchi"]
Initializing a HashSet with an another HashSet :
It is achieved with the same HashSet constructor which receives another collection as an argument and adds all its element to the HashSet.
// Program : import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; public class Main { public static void main(String[] args) { // A new HashSet of String objects created HashSet<String> newSet = new HashSet<>(); // Elements added in hashset newSet.add("Puri"); newSet.add("Goa"); newSet.add("Kochi"); newSet.add("Ranchi"); System.out.println("set Of Strings = " + newSet); // A new Set created and initialized it with existing HashSet HashSet<String> newStrSet = new HashSet<>(newSet); newSet.add("Delhi"); newSet.add("Noida"); System.out.println(""); System.out.println("new String Set = " + newSet); } }
Output : set Of Strings = [Ranchi, Kochi, Goa, Puri] new String Set = [Delhi, Ranchi, Kochi, Goa, Puri, Noida]