Java HashSet Example| Methods Explained with Code

Java HashSet Example| Methods Explained with Code

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.

What is a HashSet?

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:

  • HashSet in Java does not allow duplicate entries of elements. In case, we try to add a duplicate element, then the existing element value will be overridden.
  • It does not maintain any order of insertion, i.e. when one tries to iterate and display the elements in HashSet, every time the values in HashSet will be displayed in any random order.
  • HashSet permits the insertion of null values and is non-synchronized.

After knowing the very bit of an HashSet, let us check out how to create an HashSet.

How to create a 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.

Iterating an HashSet

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

Methods of Java HashSet

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.

  1. boolean add(Object e)
    adds a specified element to the end of the set.
  2. void clear()
    removes all the elements in the Set at once.
  3. boolean remove(Object e)
    removes the specified element from the set.
  4. Object clone()
    creates a shadow copy of the HashSet.
  5. boolean contains(Object e)
    searches for the element in the HashSet and returns true if the element is found, else returns false.
  6. boolean isEmpty()
    checks if the HashSet is empty or not. If empty then returns true, else returns false.
  7. int size()
    returns the size of the HashSet.

Varied operations that can be performed on HashSet.

Let’s check one-by-one by taking Java HashSet example.

1. Adding elements in HashSet

One can add elements in HashSet with the help of add() and addAll() methods.

What is the difference between add() and addAll()?

  • add(Object e)
    It adds a specified element to the Set.
  • addAll(Collection<? extends E> e)
    It adds a specified form of Collection to HashSet.

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]

2. Accessing elements in HashSet

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

3. Removing elements from HashSet

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()?

  • remove(Object e)
    removes the specified element from the set.
  • removeAll()
    removes all the elements from the set.
  • clear()
    removes all the elements from the set at once.

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:= []

4. Set Operations

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()?

  • retainAll()
    to perform intersection of two sets, this method can be used.
  • addAll()
    to perform a union of two different sets, this method can be used.
  • removeAll()
    to find the difference between two sets, this method can be used.

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]

5. Other methods

HashSet also provides us with few more methods and functionalities, for instance,

What is the difference between size(), isEmpty() and contains()?

  • size()
    returns the size of the set.
  • isEmpty()
    checks if the set is empty or has any elements if empty then returns true else false.
  • contains()
    searches for the specific element in the set and returns true if it exists else false.

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 !

Leave a Reply

Your email address will not be published. Required fields are marked *