Remove Element from HashSet in Java

In this article, we will discuss how to remove elements from a HashSet in Java. We will cover various methods to achieve this, providing examples to demonstrate their usage.

Table of Contents

  1. Introduction
  2. Using remove Method
  3. Using removeAll Method
  4. Using clear Method
  5. Removing Elements During Iteration
  6. Complete Example
  7. Conclusion

Introduction

A HashSet in Java is a part of the Java Collections Framework and implements the Set interface. It allows for efficient storage and retrieval of unique elements. There are several ways to remove elements from a HashSet.

Using remove Method

The remove method is used to remove a specific element from the HashSet. It returns true if the element was successfully removed, and false if the element was not present in the set.

Example

import java.util.HashSet;

public class RemoveElement {
    public static void main(String[] args) {
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Removing an element
        boolean isRemoved = fruits.remove("Banana");
        System.out.println("Is 'Banana' removed? " + isRemoved);
        System.out.println("HashSet after removal: " + fruits);
    }
}

Output:

Is 'Banana' removed? true
HashSet after removal: [Apple, Orange]

Using removeAll Method

The removeAll method is used to remove all elements from the HashSet that are contained in the specified collection. It returns true if the set changed as a result of the call.

Example

import java.util.HashSet;
import java.util.List;

public class RemoveAllElements {
    public static void main(String[] args) {
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");

        // Creating a collection of elements to remove
        List<String> toRemove = List.of("Banana", "Orange");

        // Removing all specified elements
        boolean isChanged = fruits.removeAll(toRemove);
        System.out.println("Is HashSet changed? " + isChanged);
        System.out.println("HashSet after removeAll: " + fruits);
    }
}

Output:

Is HashSet changed? true
HashSet after removeAll: [Apple, Grapes]

Using clear Method

The clear method is used to remove all elements from the HashSet, leaving it empty.

Example

import java.util.HashSet;

public class ClearHashSet {
    public static void main(String[] args) {
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

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

Output:

HashSet after clear: []

Removing Elements During Iteration

Elements can also be removed from a HashSet during iteration using an Iterator.

Example

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

public class RemoveDuringIteration {
    public static void main(String[] args) {
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Banana");

        // Creating an iterator
        Iterator<String> iterator = fruits.iterator();

        // Iterating and removing "Banana" from the HashSet
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            if ("Banana".equals(fruit)) {
                iterator.remove();
            }
        }

        // Printing the HashSet after removal
        System.out.println("HashSet after removing 'Banana': " + fruits);
    }
}

Output:

HashSet after removing 'Banana': [Apple, Orange]

Complete Example

Here's a complete example that demonstrates all the methods for removing elements from a HashSet.

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

public class RemoveElementsFromHashSet {
    public static void main(String[] args) {
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");

        // Removing an element
        boolean isRemoved = fruits.remove("Banana");
        System.out.println("Is 'Banana' removed? " + isRemoved);
        System.out.println("HashSet after removal: " + fruits);

        // Removing all specified elements
        List<String> toRemove = List.of("Orange", "Grapes");
        boolean isChanged = fruits.removeAll(toRemove);
        System.out.println("Is HashSet changed? " + isChanged);
        System.out.println("HashSet after removeAll: " + fruits);

        // Adding elements back for clear example
        fruits.add("Banana");
        fruits.add("Orange");
        System.out.println("HashSet before clear: " + fruits);

        // Clearing the HashSet
        fruits.clear();
        System.out.println("HashSet after clear: " + fruits);

        // Adding elements back for iteration example
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Creating an iterator
        Iterator<String> iterator = fruits.iterator();

        // Iterating and removing "Banana" from the HashSet
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            if ("Banana".equals(fruit)) {
                iterator.remove();
            }
        }

        // Printing the HashSet after removal
        System.out.println("HashSet after removing 'Banana' during iteration: " + fruits);
    }
}

Output:

Is 'Banana' removed? true
HashSet after removal: [Apple, Orange, Grapes]
Is HashSet changed? true
HashSet after removeAll: [Apple]
HashSet before clear: [Apple, Banana, Orange]
HashSet after clear: []
HashSet after removing 'Banana' during iteration: [Apple, Orange]

Conclusion

Removing elements from a HashSet in Java can be done using various methods, including remove, removeAll, clear, and during iteration with an Iterator. This guide provided examples to demonstrate the usage of these methods in different scenarios. By understanding these concepts, you can efficiently manage elements in your HashSet.

Comments