loading...
Cover image for Understanding HashSet In Java

Understanding HashSet In Java

its_ayush24 profile image Ayush Agarwal Originally published at ayushdev.com ・4 min read

When we talk about Data Structures and Algorithms(DSA), big names like Array, Tree, Linked List, and Dynamic Programming come to mind. But as everywhere, some underdogs are as significant as the highly heard of ones.

One such underdog Data Structure is HashSet. It is a simple Data Structure, easy to understand, and is very useful in solving coding related problems.

So, suppose you are into Competitive Programming or like to solve DSA problems. In that case, this blog might be beneficial to you in the future.

**Important Note: **

Basic knowledge of Java language will help you understand the blog better!!

What is HashSet?

As evident from the name, it works on the basic principles of a Set. It is a class interface in Java. This class does not prevent iteration order. That is the order of the elements not maintained when inserted into HashSet. Null elements are allowed in it, and HashSet will enable us to perform different tasks like add, remove, size in constant time.
We will dive more into it in the later parts of this blog.

We can implement a HashSet class using LinkedList and other Data Structures to understand more profound concepts. In the world of competitive programming, we use an inbuilt java HashSet collection, which serves most of our purposes.

Not only this collection helps us save the time of creating a HahSet from scratch, but it also enables us to perform several operations on it very quickly. Let's start looking into them with examples.
There are many operations to keep in mind, but in this blog, I will talk only about the ones that are most essential and are required frequently.

The operations which I'll be talking about are:

  1. Add
  2. Remove
  3. Size
  4. isEmpty
  5. Contains

Various Operations on HashSet

1. Add

'Add' method allows us to insert elements into the HashSet. The order of insertion is not maintained and also duplicate entries are not allowed. HashSet automatically removes duplicates.

*Example: *

// Java program to demonstrate working of Add method in a HashSet 
import java.util.*; 

class Main { 
    public static void main(String[] args) 
    { 
        HashSet<Integer> set = new HashSet<Integer>(); 
        set.add(1); 
        set.add(2); 
        set.add(3); 
        set.add(3); // intentionally adding duplicate elements 

        // Printing the HashSet 
        System.out.println(set);

        // Printing the elements of HashSet iteratively
        System.out.println("Printing elements iteratively:");
        for(int i:set){
               System.out.print(i+" ");
        }
    } 
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

[1, 2, 3]
Printing elements iteratively
1 2 3 
Enter fullscreen mode Exit fullscreen mode

From the output, we can observe that duplicate '3', which we added intentionally, was removed by HashSet.

2. Remove:

It allows us to remove elements from our HashSet.
*Example: *

// Java program to demonstrate working of Remove method in a HashSet 
import java.util.*; 

class Main { 
    public static void main(String[] args) 
    { 
        HashSet<Integer> set = new HashSet<Integer>(); 
        set.add(1); 
        set.add(2); 
        set.add(3); 
        set.add(3);

        // Printing the elements of HashSet iteratively
        System.out.println("Printing elements:");
        for(int i:set){
               System.out.print(i+" ");
        }
        // Removing element using remove()!
        set.remove(2);
        //Printing the elements of the Set again
        System.out.println();
        System.out.println("Printing elements after removing 2:");
        for(int i:set){
                System.out.print(i+" ");
        }
    } 
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Printing elements:
1 2 3 
Printing elements after removing 2:
1 3 
Enter fullscreen mode Exit fullscreen mode

3. Size

Evident from the name itself, 'size()' tells us the HashSet size, i.e., number of elements in it.
*Example: *

// Java program to demonstrate working of Size method in a HashSet 
import java.util.*; 

class Main { 
    public static void main(String[] args) 
    { 
        HashSet<Integer> set = new HashSet<Integer>(); 
        set.add(1); 
        set.add(2); 
        set.add(3); 
        set.add(3);

        // Printing the elements of HashSet iteratively
        System.out.println("Printing elements:");
        for(int i:set){
               System.out.print(i+" ");
        }
        System.out.println();
        // Getting size of HashSet using size() !!
        System.out.println("Size of the HashSet:");
        System.out.println(set.size());
    } 
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Printing elements:
1 2 3 
Size of the HashSet:
3
Enter fullscreen mode Exit fullscreen mode

4. isEmpty:

'isEmpty()' operation is used to check whether the set is empty or not. Unlike the above operations isEmpty() returns a boolean that is either 'true' or a 'false'.
*Example: *

// Java code to illustrate HashSet.isEmpty() method 
import java.util.*; 
import java.util.HashSet; 

public class HashSetDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<Integer> set = new HashSet<Integer>(); 
        set.add(1); 
        set.add(2); 
        set.add(3); 
        set.add(3);
        // Checking whether the HashSet is Empty or not !!
        System.out.println(set.isEmpty());
    } 
} 

Enter fullscreen mode Exit fullscreen mode

OUTPUT:

false
Enter fullscreen mode Exit fullscreen mode

5. Contains:

'set.contains()' is used to check whether the HashSet contains a particular element or not. And similar to 'isEmpty', Contains also returns a boolean.

*Example: *

// Java code to illustrate HashSet.contains() method 
import java.util.*; 
import java.util.HashSet; 

public class HashSetDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<Integer> set = new HashSet<Integer>(); 
        set.add(1); 
        set.add(2); 
        set.add(3); 
        set.add(3);
        // Checking whether HashSet contains a particular element or not!!
        System.out.println(set.contains(2));
        System.out.println(set.contains(5));
    } 
} 
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

true
false
Enter fullscreen mode Exit fullscreen mode

So this was all about HashSets. Next, I'll list out a few types of problems where HashSets help a lot.

  • Problems related to finding duplicates/removing duplicates.
  • Problems on finding frequency/frequency of non repeating element.
  • Union and Intersection problems.

These are a few of the most common problems where HashSets can be used. Of course, they are helpful in many other places too, which you will know when you come across problems.

With these, we come to the end of this blog. I hope you have some basic ideas and understanding after reading this.

Also for a detailed study you can head over to articles on GeeksForGeeks or W3Schools.

Discussion

pic
Editor guide