Java Set remove() example

In this guide, you will learn about the Set remove() method in Java programming and how to use it with an example.

1. Set remove() Method Overview

Definition:

The remove() method of the Java Set interface removes the specified element from the set if it is present.

Syntax:

boolean wasRemoved = set.remove(Object o);

Parameters:

- o - element to be removed from the set, if present.

Key Points:

- The method returns true if the set contained the specified element.

- If the element is not found in the set, the set remains unchanged, and the method returns false.

- Only one instance of the specified element is removed, but since a set does not allow duplicate elements, this will remove the only occurrence of the element.

2. Set remove() Method Example

import java.util.HashSet;
import java.util.Set;

public class SetRemoveExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();

        // Adding some elements to the set
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Attempt to remove an element that exists
        boolean appleRemoved = fruits.remove("Apple");
        System.out.println("Was Apple removed? : " + appleRemoved);  // true
        System.out.println("Set after removing Apple: " + fruits);  // [Banana, Cherry]

        // Attempt to remove an element that doesn't exist
        boolean mangoRemoved = fruits.remove("Mango");
        System.out.println("Was Mango removed? : " + mangoRemoved);  // false
        System.out.println("Set after attempting to remove Mango: " + fruits);  // [Banana, Cherry]
    }
}

Output:

Was Apple removed? : true
Set after removing Apple: [Banana, Cherry]
Was Mango removed? : false
Set after attempting to remove Mango: [Banana, Cherry]

Explanation:

In this example:

1. We create a HashSet of fruits and add three elements to it: "Apple", "Banana", and "Cherry".

2. We then attempt to remove "Apple", which is present in the set. The remove() method returns true and the element is removed.

3. Next, we attempt to remove "Mango", which is not present in the set. The remove() method returns false and the set remains unchanged.

The remove() method provides an effective way to remove individual elements from a set. However, caution should be taken when removing elements from a set while iterating over it, as it can lead to the ConcurrentModificationException. It's recommended to use an iterator's remove() method or other safe approaches in such scenarios.

Related Java Set interface methods

Java Set add() example
Java Set contains() example
Java Set isEmpty() example
Java Set remove() example
Java Set size() example

Comments