In the previous tutorials, we have learned about the basics of Collections, the varied methods and operations that are supported by HashMap and ArrayList in Java.
Now let’s dive into Java HashSet and know about their methods and operations in Java.
I will explain each point with Java HashSet example.
Table of Contents
The HashSet class of Java is an implementation of the Set interface which uses the hash table for storage purposes. In simple words, a HashSet generally stores elements with the help of hashing technique.
Properties of HashSet:
After knowing the very bit of an HashSet, let us check out how to create an HashSet.
Proceeding further, this is how we can create a HashSet in Java,
HashSet<Type> hashSetName = new HashSet<>();
Where, Type equals to any form of data type or Object.
For example,
HashSet integerSet = new HashSet<>(); // creating an Integer HashSet. HashSet bookSet = new HashSet<>(); // creating an HashSet of Book.
Now, as we know how to create an HashSet, let us look into a basic example to create an HashSet and then print it.
Example: We will be creating a set of fruits called fruitSet that will store values in the form of String. Sticking to the basics, to create a HashSet we need to first import java.util.HashSet
or its superclass.
import java.util.HashSet;
import java.util.Iterator;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> fruitSet = new HashSet<>();
//Adding elements to the HashSet.
fruitSet.add("Mango");
fruitSet.add("Apple");
fruitSet.add("Orange");
//Printing the elements in the HashSet.
System.out.println("Values in the set are:= "+ fruitSet);
//Iterating the HashSet using for-each loop.
System.out.println("====Using for-each loop====");
for(String fruits : fruitSet) {
System.out.println(fruits);
}
//Iterating the HashSet using Iterator.
System.out.println("====Using Iterator====");
Iterator<String> itr = fruitSet.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
//Iterating the HashSet using forEach method of Java 8.
System.out.println("====Using forEach method of Java 8====");
fruitSet.forEach((fruit) -> System.out.println(fruit));
}
}
Output:
The expected output of the above program is as follows:
Values in the set are:= [Apple, Mango, Orange] ====Using for-each loop==== Apple Mango Orange ====Using Iterator==== Apple Mango Orange ====Using forEach method of Java 8==== Apple Mango Orange
In the above basic example, we have observed the use of add()
and iterate()
method in HashSet.
HashSet in Java has a varied number of methods that allow different operations to be performed.
Let us now take a small ride to methods supported by HashSet and know a bit about them.
Varied operations that can be performed on HashSet.
Let’s check one-by-one by taking Java HashSet example.
One can add elements in HashSet with the help of add()
and addAll()
methods.
What is the difference between add() and addAll()?
Coding Example:
Below is an example that will help in understanding the adding of elements to HashSet better.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> vegetableSet = new HashSet<>();
//Adding elements to the HashSet.
vegetableSet.add("Potato");
vegetableSet.add("Onion");
vegetableSet.add("Broccoli");
//Printing the elements in the HashSet.
System.out.println("Values in the set are:= "+ vegetableSet);
//Creating a sample HashSet.
HashSet<String> sampleSet = new HashSet<>();
//Adding elements to the new set.
sampleSet.add("Tomato");
sampleSet.addAll(vegetableSet);
//Printing the elements in the HashSet.
System.out.println("Values in the sample HashSet are:= "+sampleSet);
}
}
Output:
The expected output of the above code snippet is:
Values in the set are:= [Potato, Broccoli, Onion] Values in the sample HashSet are:= [Potato, Broccoli, Onion, Tomato]
The elements in the HashSet can be accessed with the help of iterator()
method and for using it, we will have to import java.util.Iterator
package.
Coding Example:
How to get the values from HashSet in Java?
Below is a small example depicting the usage of iterator()
method to access HashSet elements.
import java.util.HashSet;
import java.util.Iterator;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> vegetableSet = new HashSet<>();
//Adding elements to the HashSet.
vegetableSet.add("Potato");
vegetableSet.add("Onion");
vegetableSet.add("Broccoli");
//Printing the elements in the HashSet.
System.out.println("Values in the set are:= "+ vegetableSet);
//Accessing HashSet elements with the help of iterator.
System.out.println("==Accessing elements using iterator() method==");
Iterator itr = vegetableSet.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output:
The expected output of the above code snippet is :
Values in the set are:= [Potato, Broccoli, Onion] ==Accessing elements using iterator() method== Potato Broccoli Onion
One can remove the elements from HashSet with the help of remove()
, clear()
and removeAll()
methods.
What is the difference between remove(), removeAll() and clear()?
Coding Example:
Below is an example showing removal of elements from HashSet.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> vegetableSet = new HashSet<>();
//Adding elements to the HashSet.
vegetableSet.add("Potato");
vegetableSet.add("Onion");
vegetableSet.add("Broccoli");
//Printing the elements in the HashSet.
System.out.println("Values in the set are:= "+ vegetableSet);
//Creating a sample HashSet.
HashSet<String> sampleSet = new HashSet<>();
//Adding elements to the new set.
sampleSet.add("Tomato");
sampleSet.addAll(vegetableSet);
//Printing the elements in the HashSet.
System.out.println("Values in the sample HashSet are:= "+sampleSet);
//Deleting one element from set.
vegetableSet.remove("Broccoli");
sampleSet.remove("Potato");
System.out.println("Set after removing ‘Broccoli’ := " +vegetableSet);
System.out.println("Sample Set after removing ‘Potato’ := " +sampleSet);
//Deleting all the elements from both the sets.
vegetableSet.removeAll(vegetableSet);
System.out.println("Set after deleting all the elements altogether:= "+vegetableSet);
sampleSet.clear();
System.out.println("Sample Set after deleting all the elements altogether:= "+sampleSet);
}
}
Output:
The expected output of the above program is:
Values in the set are:= [Potato, Broccoli, Onion] Values in the sample HashSet are:= [Potato, Broccoli, Onion, Tomato] Set after removing ‘Broccoli’ := [Potato, Onion] Sample Set after removing ‘Potato’ := [Broccoli, Onion, Tomato] Set after deleting all the elements altogether:= [] Sample Set after deleting all the elements altogether:= []
One can perform varied set operations like union, intersection and difference of a set using available Set class methods.
What is difference betwee retainAll(), addAll() and removeAll()?
Coding Example:
Below example will help you clear out how does it actually work…
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> vowelSet = new HashSet<>();
//Adding elements to the HashSet.
vowelSet.add("A");
vowelSet.add("E");
vowelSet.add("I");
vowelSet.add("O");
vowelSet.add("U");
//Printing the elements.
System.out.println("Values in the vowel set are:="+vowelSet);
//Creating a new Set.
HashSet<String> consonantSet = new HashSet<>();
consonantSet.add("A");
consonantSet.add("K");
consonantSet.add("P");
consonantSet.add("U");
//Printing the elements.
System.out.println("Values in the consonant set are:="+consonantSet);
//Intersection of two sets.
vowelSet.retainAll(consonantSet);
System.out.println("The result of intersection of two sets is:="+vowelSet);
//Union of two sets.
consonantSet.addAll(vowelSet);
System.out.println("Values in the set after union of sets:="+consonantSet);
//Difference between two sets.
consonantSet.removeAll(vowelSet);
System.out.println("The result of difference between two sets is :="+consonantSet);
}
}
Output:
The expected output of the above program is as follows:
Values in the vowel set are:=[A, E, U, I, O] Values in the consonant set are:=[P, A, U, K] The result of intersection of two sets is:=[A, U] Values in the set after union of sets:=[P, A, U, K] The result of difference between two sets is :=[P, K]
HashSet also provides us with few more methods and functionalities, for instance,
What is the difference between size(), isEmpty() and contains()?
Coding Example:
With the help of an example, let us find out how the above-listed methods work,
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> fruitSet = new HashSet<>();
//Adding elements to the HashSet.
fruitSet.add("Mango");
fruitSet.add("Watermelon");
fruitSet.add("Guava");
fruitSet.add("Grapes");
fruitSet.add("Banana");
fruitSet.add("Apple");
//Printing the elements in the HashSet.
System.out.println("Elements of the set are := "+fruitSet);
//To check if the set empty or not.
System.out.println("Is the set empty? "+fruitSet.isEmpty());
//Print the length of HashSet.
System.out.println("Size of the HashSet is := "+fruitSet.size());
//To check if set contains 'Orange' or not.
System.out.println("Does the set contain 'Mango' ? " +fruitSet.contains("Mango"));
}
}
Output:
The expected output of the program is:
Elements of the set are := [Guava, Apple, Grapes, Watermelon, Mango, Banana] Is the set empty? false Size of the HashSet is := 6 Does the set contain 'Mango' ? true
And that’s all about HashSet in Java. To sum up, in this tutorial we learnt about what a HashSet is, the methods it supports and the operations and functionalities a HashSet can do. I have also shared Java HashSet examples and source code.
If you have any query, feel free to ask me in comment.
Happy Learning !