Java

How to Use HashSet in Java?

Java has a collection class called HashSet that implements the Set interface which uses a hash table for storage. It is used to keep a collection of distinct elements in any arrangement. The main advantage of using HashSet is that it allows fast access to elements, as it uses hashing to store the elements. HashSet is ideal for removing duplicates and finding common elements between two sets.

This guide will illustrate the HashSet along with possible examples in Java.

How to Use HashSet in Java?

To use HashSet in Java, first import the HashSet class. After that, create a HashSet object and add elements utilizing the “add()” method. Use the remove() function to eliminate a member of the HashSet.

Users can also utilize the contains() method to compute if an element exists in the HashSet. Finally, to iterate over the elements in the HashSet, use a for-each loop.

Here are a few examples of how to use HashSet in Java:

Example 1: Removing Duplicates from an ArrayList
One common use case for HashSet is to remove duplicates from a collection. Here is an example of how to use HashSet to remove duplicates from an ArrayList:

import java.util.ArrayList;
import java.util.HashSet;

public class RemoveDuplicatesExample {
    public static void main(String[] args) {
        ArrayList listWithDuplicates = new ArrayList();
        listWithDuplicates.add("apple");
        listWithDuplicates.add("banana");
        listWithDuplicates.add("orange");
        listWithDuplicates.add("apple");
        listWithDuplicates.add("orange");

        HashSet setWithoutDuplicates = new HashSet(listWithDuplicates);
        ArrayList listWithoutDuplicates = new ArrayList(setWithoutDuplicates);

        System.out.println("List with duplicates: " + listWithDuplicates);
        System.out.println("List without duplicates: " + listWithoutDuplicates);
    }
}

The description of the above code is given below:

  • First, create an ArrayList of strings with duplicates.
  • Then, create a HashSet from the ArrayList. It is because a HashSet can only contain unique elements, this effectively removes the duplicates.
  • In the end, create a new ArrayList from the HashSet to get a list without duplicates.

Output

The output shows that duplication has been removed from the list.

Example 2: Finding Common Elements Between Two Sets
Another use case for HashSet is to find common elements between two sets. Here is an example of how to use HashSet to find common elements between two sets:

import java.util.HashSet;

public class FindCommonElementsExample { // Specify Class name
    public static void main(String[] args) {
        HashSet set1 = new HashSet();
        set1.add(1);
        set1.add(2);  // Add Values here
        set1.add(3);

        HashSet set2 = new HashSet();
        set2.add(2);
        set2.add(3);    // Add Values here
        set2.add(4);

        HashSet commonElements = new HashSet(set1);
        commonElements.retainAll(set2);

        System.out.println("Set 1: " + set1);
        System.out.println("Set 2: " + set2);
        System.out.println("Common elements: " + commonElements);
    }
}

The explanation is given below:

  • First, create two HashSet objects and add some integers to them.
  • Then, create a new HashSet object and add all elements from set1 to it.
  • After that, call the retainAll() method on this new HashSet object, passing in set2 as an argument.
  • It effectively removes any elements from the new HashSet that are not in set2, leaving only the common elements.

Output

The output shows that common elements have been found between two sets.

Conclusion

HashSet is a powerful collection class in Java used to store a set of unique elements in no particular order. It provides methods such as “add()”, “remove()”, and “contains()” to add, remove, and check for the presence of elements in the HashSet. It iterates over elements and is simple with a for-each loop. By implementing the hashCode() and equals() methods, users can also use custom objects in a HashSet.

This guide has covered all possible examples to use the HashSet in Java.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.