riven

Riven

Riven

Hashset in java with example

In Java, a HashSet is a widely used collection class that implements the Set interface. It is part of the Java Collections Framework and is designed to store unique elements without any specific order. HashSet uses a hash table for storage, allowing for fast access, insertion, and deletion of elements. 

What is HashSet?

A HashSet is a collection that implements the Set interface and allows for the storage of unique elements. Key characteristics of a HashSet include:

  1. No Duplicates: It does not allow duplicate elements. If you attempt to add a duplicate, it will be ignored.
  2. Unordered: The elements in a HashSet are not stored in any particular order. When you iterate over a HashSet, the order may vary.
  3. Null Values: HashSet can store a single null element.
  4. Fast Operations: HashSet offers average constant-time performance (O(1)) for the basic operations: add, remove, and contains.

HashSet Implementation

The HashSet class is part of the java.util package. It is backed by a hash table (actually a HashMap instance), and its performance is based on the efficiency of the hash function used.

Key Characteristics of HashSet

  • Storage Mechanism: It uses a hash table for storing elements, which helps achieve constant-time performance for basic operations.
  • Hashing: When an object is added to a HashSet, its hash code is computed. This code determines the bucket in which the object will be stored.
  • Collision Resolution: If two objects have the same hash code (collision), the HashSet will store them in the same bucket and use linked lists or other structures to maintain uniqueness.

Important Methods in HashSet

  • add(E e): Adds the specified element to the set if it is not already present.
  • remove(Object o): Removes the specified element from the set if it is present.
  • contains(Object o): Returns true if the set contains the specified element.
  • size(): Returns the number of elements in the set.
  • isEmpty(): Returns true if the set is empty.
  • clear(): Removes all elements from the set.
  • iterator(): Returns an iterator over the elements in the set.

Creating a HashSet

To create a HashSet, you need to import the class from the java.util package. You can instantiate a HashSet using its constructor.

Example: Creating a HashSet

				
					import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        HashSet<String> fruits = new HashSet<>();

        // Adding elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Banana"); // Duplicate, will be ignored

        // Displaying the HashSet
        System.out.println("Fruits: " + fruits);
    }
}
//Output:

Fruits: [Banana, Cherry, Apple]
				
			

Common Operations on HashSet

1. Adding Elements

You can add elements to a HashSet using the add() method. If you attempt to add a duplicate element, the operation will be ignored.

Example: Adding Elements

				
					fruits.add("Mango"); // Adding a new element
fruits.add("Apple"); // Attempting to add a duplicate
System.out.println("After adding: " + fruits);
				
			

2. Removing Elements

Elements can be removed from a HashSet using the remove() method. If the element is not present, the method does nothing.

Example: Removing Elements

				
					fruits.remove("Banana"); // Removing an element
System.out.println("After removing Banana: " + fruits);
				
			

3. Checking for Elements

You can check if a HashSet contains a specific element using the contains() method.

Example: Checking for Elements

				
					boolean hasApple = fruits.contains("Apple");
System.out.println("Contains Apple: " + hasApple);
				
			

4. Getting Size and Emptiness

You can find out the number of elements in a HashSet using the size() method, and check if it is empty using the isEmpty() method.

Example: Size and Emptiness

				
					System.out.println("Size of the set: " + fruits.size());
System.out.println("Is the set empty? " + fruits.isEmpty());
				
			

5. Clearing the Set

To remove all elements from a HashSet, you can use the clear() method.

Example: Clearing the Set

				
					fruits.clear();
System.out.println("After clearing: " + fruits);
				
			

Iterating Over a HashSet

You can iterate over the elements of a HashSet using several methods, such as the enhanced for loop, the iterator, or the forEach method.

Example: Iterating Using an Enhanced For Loop

				
					for (String fruit : fruits) {
    System.out.println(fruit);
}
				
			

Example: Using forEach Method

				
					fruits.forEach(fruit -> System.out.println(fruit));
				
			

Performance Considerations

Time Complexity

The average time complexity for basic operations in a HashSet is as follows:

  • Add: O(1)
  • Remove: O(1)
  • Contains: O(1)

However, in the worst case (e.g., when many collisions occur), these operations can degrade to O(n), but this is rare with a good hash function.

Memory Usage

HashSet uses more memory compared to other set implementations due to its underlying hash table structure. Each element requires additional space for storing the hash code and pointers for handling collisions.

Use Cases for HashSet

  1. Unique Data Storage: Use HashSet when you need to store a collection of unique elements, such as user IDs or email addresses.
  2. Fast Lookups: When you require frequent checks for membership, HashSet provides efficient performance.
  3. Removing Duplicates: Use HashSet to eliminate duplicates from a collection of items, such as a list of products.

Advanced Operations with HashSet

Union of Two HashSets

You can perform a union of two HashSet instances by adding all elements of one set to another.

Example: Union of Two HashSets

				
					HashSet<String> set1 = new HashSet<>();
set1.add("A");
set1.add("B");

HashSet<String> set2 = new HashSet<>();
set2.add("B");
set2.add("C");

// Performing union
HashSet<String> unionSet = new HashSet<>(set1);
unionSet.addAll(set2);
System.out.println("Union: " + unionSet);
				
			

Intersection of Two HashSets

You can find the intersection of two sets using the retainAll() method, which retains only the elements that are present in both sets.

Example: Intersection of Two HashSets

				
					HashSet<String> intersectionSet = new HashSet<>(set1);
intersectionSet.retainAll(set2);
System.out.println("Intersection: " + intersectionSet);
				
			

Difference of Two HashSets

To find the difference between two sets, you can use the removeAll() method, which removes all elements from one set that are present in another.

Example: Difference of Two HashSets

				
					HashSet<String> differenceSet = new HashSet<>(set1);
differenceSet.removeAll(set2);
System.out.println("Difference: " + differenceSet);
				
			

Real-World Application Example: Unique User Registration

Let’s create a simple console application to manage user registrations. This application will ensure that each username is unique.

UserRegistration Class

				
					import java.util.HashSet;
import java.util.Scanner;

public class UserRegistration {
    private HashSet<String> usernames;

    public UserRegistration() {
        usernames = new HashSet<>();
    }

    public void registerUser(String username) {
        if (usernames.add(username)) {
            System.out.println("User registered: " + username);
        } else {
            System.out.println("Username already taken: " + username);
        }
    }

    public void displayUsers() {
        System.out.println("Registered Users:");
        for (String username : usernames) {
            System.out.println("- " + username);
        }
    }

    public static void main(String[] args) {
        UserRegistration registration = new UserRegistration();
        Scanner scanner = new Scanner(System.in);
        String command;

        System.out.println("User Registration System");
        System.out.println("Commands: register [username], view, exit");

        while (true) {
            System.out.print("Enter command: ");
            command = scanner.nextLine();
            String[] parts = command.split(" ", 2);
            switch (parts[0]) {
                case "register":
                    if (parts.length > 1) {
                        registration.registerUser(parts[1]);
                    } else {
                        System.out.println("Please specify a username.");
                    }
                    break;
                case "view":
                    registration.displayUsers();
                    break;
                case "exit":
                    System.out.println("Exiting User Registration System.");
                    scanner.close();
                    return;
                default:
                    System.out.println("Unknown command.");
            }
        }
    }
}
				
			

Explanation of the User Registration System

  1. UserRegistration Class: This class maintains a HashSet of usernames and provides methods for registering users and displaying registered usernames.
  2. User Interaction: The main method provides a simple command-line interface for users to register and view usernames.
  3. Commands:
    • register [username]: Registers a new user if the username is unique.
    • view: Displays all registered usernames.
    • exit: Exits the application

Related topic

Dependency injection in spring
Dependency injection in spring with example Dependency Injection (DI) is a design pattern that helps...
Java executor framework
Java executor framework with example The Java Executor Framework, introduced in Java 5, provides a powerful...
Java unchecked exception
Unchecked Exception in Java In Java, exceptions are categorized into two main types: checked and unchecked...
Functional interface in java
What is a Functional Interface in java 8? A functional interface in Java is an interface that contains...
parallel stream in java
Parallel Stream in java Parallel streams automatically split the source data into multiple chunks and...
Java scanner user input
Java scanner for user input he Scanner class in Java is a powerful utility for reading input from various...
Hierarchical inheritance java
Hierarchical inheritance java Hierarchical inheritance occurs when one superclass has multiple subclasses....
Filter stream java
Filter stream java with example What is a Stream in Java? A Stream in Java is a sequence of elements...
Getter and setter in java
Getter and setter in java Getters in java A getter is a method that retrieves (or “gets”)...
Set in java (Interface)
Set in java example In Java, the Set interface is part of the Java Collections Framework and represents...