Remove Element from HashSet in Java

A HashSet in Java is a collection that does not allow duplicate elements and does not maintain any specific order of its elements. Sometimes, you may need to remove an element from a HashSet. This tutorial will guide you through the process of removing an element from a HashSet in Java, covering key points, use cases, best practices, and including examples with output.

Key Points

  • HashSet is part of the java.util package.
  • The remove() method is used to remove an element from a HashSet.
  • The remove() method returns true if the element was present and successfully removed, otherwise it returns false.

Use Cases

  • Dynamic collections: When you need a collection that supports fast removal of elements.
  • Filtering: Removing elements based on some condition (e.g., filtering out invalid entries).
  • Updating collections: Dynamically updating a set of elements where duplicates are not allowed.

Best Practices

  • Always check if the element exists before attempting to remove it, especially if subsequent operations depend on the presence of the element.
  • Be aware that removing an element while iterating over the HashSet using an enhanced for-loop can lead to ConcurrentModificationException. Use an iterator's remove() method if removal during iteration is necessary.

Example with Output

Here is a step-by-step example demonstrating how to remove an element from a HashSet:

Step-by-Step Example

  1. Import the java.util.HashSet package:

    import java.util.HashSet;
    
  2. Create a HashSet and add some elements:

    public class HashSetExample {
        public static void main(String[] args) {
            HashSet<String> names = new HashSet<>();
    
            // Adding elements to the HashSet
            names.add("Ramesh");
            names.add("Suresh");
            names.add("Mahesh");
            names.add("Rajesh");
    
            // Displaying the HashSet
            System.out.println("Original HashSet: " + names);
        }
    }
    
  3. Remove an element from the HashSet:

    public class HashSetExample {
        public static void main(String[] args) {
            HashSet<String> names = new HashSet<>();
    
            // Adding elements to the HashSet
            names.add("Ramesh");
            names.add("Suresh");
            names.add("Mahesh");
            names.add("Rajesh");
    
            // Displaying the HashSet
            System.out.println("Original HashSet: " + names);
    
            // Removing an element
            boolean isRemoved = names.remove("Mahesh");
    
            // Checking if the element was removed
            if (isRemoved) {
                System.out.println("Element 'Mahesh' was removed.");
            } else {
                System.out.println("Element 'Mahesh' was not found.");
            }
    
            // Displaying the HashSet after removal
            System.out.println("HashSet after removal: " + names);
        }
    }
    

Output

Original HashSet: [Ramesh, Suresh, Mahesh, Rajesh]
Element 'Mahesh' was removed.
HashSet after removal: [Ramesh, Suresh, Rajesh]

Real-time Example with CRUD Operations

Here’s a more comprehensive example demonstrating CRUD operations (Create, Read, Update, Delete) using HashSet:

import java.util.HashSet;
import java.util.Iterator;

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

        // Create - Adding elements to the HashSet
        employees.add("Anil");
        employees.add("Sunil");
        employees.add("Vijay");
        employees.add("Ajay");

        // Read - Displaying the HashSet
        System.out.println("Employee Set: " + employees);

        // Update - Checking if an element exists and updating (removing and adding)
        if (employees.contains("Sunil")) {
            employees.remove("Sunil");
            employees.add("Sunil Kumar");
            System.out.println("Updated 'Sunil' to 'Sunil Kumar'.");
        }

        // Displaying the HashSet after update
        System.out.println("Employee Set after update: " + employees);

        // Delete - Removing an element
        boolean isRemoved = employees.remove("Vijay");

        // Checking if the element was removed
        if (isRemoved) {
            System.out.println("Element 'Vijay' was removed.");
        } else {
            System.out.println("Element 'Vijay' was not found.");
        }

        // Displaying the HashSet after removal
        System.out.println("Employee Set after removal: " + employees);

        // Iterate and display using Iterator
        System.out.println("Iterating over Employee Set:");
        Iterator<String> iterator = employees.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Output

Employee Set: [Anil, Sunil, Vijay, Ajay]
Updated 'Sunil' to 'Sunil Kumar'.
Employee Set after update: [Anil, Sunil Kumar, Vijay, Ajay]
Element 'Vijay' was removed.
Employee Set after removal: [Anil, Sunil Kumar, Ajay]
Iterating over Employee Set:
Anil
Sunil Kumar
Ajay

Conclusion

Removing an element from a HashSet in Java is straightforward using the remove() method. This tutorial provided a detailed explanation, examples, and a real-time CRUD operation example to help you understand the concept thoroughly. Use these practices to effectively manage and manipulate collections in your Java applications.

Comments