top

Search

Java Tutorial

.

UpGrad

Java Tutorial

HashSet Java

Introduction

Welcome to this tutorial on HashSet in Java! If you're a programming enthusiast looking to explore an essential data structure for collection management, you're in the right place. HashSet Java allows you to manage collections of elements efficiently and is a convenient and efficient paradigm for storing elements while maintaining uniqueness.

Its foundation lies in a robust data structure known as a hash table. HashSet orchestrates seamless organization and access within the collection by assigning a distinct hash code to each element. This intelligent approach empowers the data structure to perform basic operations such as addition, removal, and retrieval with constant-time efficiency, as you will understand with some HashSet Java examples. 

The beauty of HashSet Java 8 lies in its ability to simplify your programming journey. With HashSet methods in Java, you can effortlessly append new elements, verify the presence of an element, or selectively eliminate items. The burden of dealing with duplicates is entirely alleviated, leaving you with a streamlined approach to managing collections of any HashSet size in Java.

Overview

This tutorial provides a comprehensive overview of HashSet Java. You will learn about a hash table's features, benefits, and implementation. You will also explore the efficient storage, fast operations, and handling of duplicate elements, enabling you to manage collections in Java effectively.

Java HashSet Features

Here are the features of HashSet in Java:

  • Uniqueness: HashSet does not allow duplicate elements. It ensures that each element in the set is unique.

  • Unordered: The elements in a HashSet are not ordered. There is no guarantee of the order in which the elements will be stored or retrieved.

  • Performance: HashSet provides constant-time performance for basic operations like add, remove, and contains, assuming a good hash function is used.

  • No Indexing: HashSet does not provide indexing-based access to elements. You cannot access elements by their position in the set.

Declaration of HashSet

Here is the declaration of HashSet:

HashSet<T> set = new HashSet<>();

In the syntax above, T represents the type of elements that the HashSet will hold. Replace T with the desired type, such as Integer, String, or a custom class.

Constructors of HashSet Class

Here are the constructors of the HashSet Class:

  • HashSet(): Creates an empty HashSet with the default initial capacity (16) and the default load factor (0.75).

  • HashSet(int initialCapacity): Creates an empty HashSet with the specified initial capacity and the default load factor.

  • HashSet(int initialCapacity, float loadFactor): Creates an empty HashSet with the specified initial capacity and load factor.

  • HashSet(Collection<? extends T> c): Creates a HashSet containing the elements of the specified collection.

HashSet Java Example

import java.util.HashSet;

public class upGradTutorials {
    public static void main(String[] args) {
        // Create a HashSet
        HashSet<String> set = new HashSet<>();

        // Add elements to the HashSet
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");
        set.add("Mango");
        set.add("Grapes");

        // Print the HashSet
        System.out.println("HashSet: " + set);

        // Check if an element exists in the HashSet
        boolean containsBanana = set.contains("Banana");
        System.out.println("Contains Banana? " + containsBanana);

        // Remove an element from the HashSet
        boolean removedOrange = set.remove("Orange");
        System.out.println("Removed Orange? " + removedOrange);

        // Print the size of the HashSet
        System.out.println("Size of HashSet: " + set.size());

        // Iterate over the elements of the HashSet
        System.out.println("Elements of HashSet:");
        for (String element : set) {
            System.out.println(element);
        }

        // Clear the HashSet
        set.clear();
        System.out.println("HashSet after clear: " + set);
    }
}

In this example, we create a HashSet called set to store strings. We add elements to the HashSet using the add() method, and then we print the HashSet using the println() method. We demonstrate checking if an element exists in the HashSet using the contains() method and removing an element using the remove() method. We also show how to get the size of the HashSet using the size() method.

We use a for-each loop to iterate over the elements of the HashSet. Finally, we use the clear() method to remove all elements from the HashSet.

The Hierarchy of HashSet

The hierarchy of HashSet starts with the Object class, which is the root of the Java class hierarchy.

Next, HashSet extends the AbstractCollection class, which provides a partial implementation of the Collection interface. AbstractCollection implements the Iterable interface, allowing elements in the collection to be iterated.

HashSet extends the AbstractSet class, an abstract implementation of the Set interface. AbstractSet provides common set operations such as adding, removing, and checking for the presence of elements in the set.

Finally, HashSet is the concrete implementation of the Set interface. It represents an unordered collection of unique elements. HashSet uses a hash table data structure to store elements, providing constant-time performance for basic operations such as adding, removing, and searching for elements.

This is the hierarchy of HashSet in Java:

java.lang.Object
    └─ java.util.AbstractCollection<E>
        └─ java.util.AbstractSet<E>
            └─ java.util.HashSet<E>

Internal Working of a HashSet

Here is the internal working of a HashSet:

  • HashSet internally uses a HashMap to store its elements.

  • Each element in the HashSet is stored as a key in the underlying HashMap with a dummy value.

  • When an element is added to the HashSet, it is added as a key in the underlying HashMap with a fixed dummy value.

  • The hash value of the element determines the bucket (index) in the HashMap where it will be stored.

  • If two elements have the same hash value, they will be stored in the same bucket as separate entries.

  • When checking for the presence of an element in the HashSet, the hash value of the element is used to find the bucket, and then the actual equality comparison is performed.

  • The internal HashMap handles collisions and resizes as needed to maintain a good performance.

Methods in HashSet

Here are some important methods in HashSet:


Performing Various Operations on HashSet

Adding Elements in HashSet

import java.util.HashSet;

public class upGradTutorials {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("apple");
        set.add("banana");
        set.add("orange");

        System.out.println(set); // Output: [orange, apple, banana]
    }
}

In this example, we create a HashSet of type String and add three elements: "apple", "banana", and "orange". The add() method is used to add elements to the HashSet.

Removing Elements in HashSet

import java.util.HashSet;

public class upGradTutorials {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("apple");
        set.add("banana");
        set.add("orange");

        set.remove("banana");

        System.out.println(set); // Output: [orange, apple]
    }
}

Here, we remove the element "banana" from the HashSet using the remove() method. After removal, the HashSet will contain "apple" and "orange" elements.

Iterating through the HashSet

import java.util.HashSet;

public class upGradTutorials {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("apple");
        set.add("banana");
        set.add("orange");

        for (String item : set) {
            System.out.println(item);
        }
        // Output:
        // orange
        // apple
        // banana
    }
}

In this example, we iterate through the HashSet using a for-each loop. Each element in the HashSet is printed using the println() method. The iteration order is not guaranteed to be the same as the insertion, as HashSet does not maintain any specific order for its elements.

Difference between List and Set

List

Set

Allows duplicate elements.

Does not allow duplicate elements.

Elements are ordered and have an index-based position.

Elements are not ordered and do not have a specific position.

Provides methods like get(), set(), and remove() to access and manipulate elements by their index.

Provides methods like add(), remove(), and contains() to add, remove, and check for the presence of elements.

Implementations include ArrayList, LinkedList, etc.

Implementations include HashSet, TreeSet, etc.

Create HashSet from a Collection

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

public class upGradTutorials {
    public static void main(String[] args) {
        // Create a collection
        Collection<String> collection = new ArrayList<>();
        collection.add("apple");
        collection.add("banana");
        collection.add("orange");

        // Create a HashSet from the collection
        HashSet<String> set = new HashSet<>(collection);

        System.out.println(set); // Output: [banana, orange, apple]
    }
}

In this program, a HashSet is created and initialized with elements from an existing collection. The addAll() method is used to add all elements from the collection to the HashSet, effectively creating a HashSet with the same elements as the collection.

Java HashSet Example: Ignoring Duplicate Elements

import java.util.HashSet;

public class upGradTutorials {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();

        // Add elements, ignoring duplicates
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("apple"); // Ignored because it's a duplicate

        System.out.println(set); // Output: [orange, apple, banana]
    }
}

This program demonstrates how HashSet automatically handles duplicate elements. Multiple elements with the same value are added to the HashSet, but only unique values are stored. When printing the HashSet, duplicate elements are ignored, resulting in a set with distinct values.

Java HashSet Example: Book

import java.util.HashSet;

class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    @Override
    public int hashCode() {
        return title.hashCode() + author.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Book other = (Book) obj;
        return title.equals(other.title) && author.equals(other.author);
    }

    @Override
    public String toString() {
        return "Book [title=" + title + ", author=" + author + "]";
    }
}

public class upGradTutorials {
    public static void main(String[] args) {
        HashSet<Book> bookSet = new HashSet<>();

        // Create book objects
        Book book1 = new Book("Harry Potter", "J.K. Rowling");
        Book book2 = new Book("The Great Gatsby", "F. Scott Fitzgerald");
        Book book3 = new Book("Harry Potter", "J.K. Rowling"); // Duplicate book

        // Add books to the set
        bookSet.add(book1);
        bookSet.add(book2);
        bookSet.add(book3); // Ignored because it's a duplicate based on equals() and hashCode()

        System.out.println(bookSet);
    }
}

This program illustrates the usage of a HashSet to store Book objects. Each Book object is uniquely identified by its title and author. The hashCode() and equals() methods of the Book class are overridden to ensure proper comparison and uniqueness in the HashSet.

Conclusion 

HashSet Java is a powerful and versatile data structure that simplifies collections management while ensuring uniqueness. HashSet automatically handles duplicates, making it a reliable choice for maintaining distinct values.

The flexibility of HashSet reflects in various scenarios, such as removing duplicates from a collection or quickly checking for membership. Its usage eliminates the need for manual duplicate checks and simplifies collection manipulation tasks. Although HashSet does not maintain a specific order of elements, its benefits of efficiency and automatic uniqueness make it a valuable tool in Java programming. If order preservation is a requirement, LinkedHashSet can be used as an alternative.

By understanding the capabilities and best practices of HashSet, you can harness its power to efficiently manage collections and enhance the performance of your Java applications. 

FAQs

  1. What is a HashSet in Javascript?

A HashSet JavaScript collection stores unique elements and maintains no specific order. It uses a hash table to provide efficient storage and fast operations like adding, removing, and searching elements.

  1. Can I store null values in a HashSet Java 8?

Yes, HashSet allows storing null values. It treats null as a valid element and handles it without issues during addition, removal, or retrieval operations.

  1. Do we have HashSet in Python?

No, HashSet is not a built-in data structure in Python. However, Python offers a data structure called a set, which provides similar functionality for storing unique elements and performing set operations like union, intersection, and difference.

Leave a Reply

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