What is the Set.remove() method in Java?

Share

Overview

The Set.remove() method is present in the Set interface inside the java.util package. This method removes only the specified element from the Set.

Example

Let’s understand with the help of an example.

Let’s suppose that the Set contains the following: [1, 8, 5, 3, 0]. We execute the below statements on this set:

  • Set1.remove(8);
  • Set1.remove(0);

After using the remove() method, the Set contains [1, 5, 3].

Syntax

public boolean remove(Object obj)

Parameters

The Set.remove() has one parameter:

  • obj: It is a HashSet, TreeSet, or NavigableSet type Object that needs to be removed from the Set. As Set is an interface, it needs to be implemented by one of its implementing classes.

Return value

The Set.remove() method returns true if the Set gets changed.

Example

Let’s look at a code example below.

import java.util.Set;
import java.util.HashSet;
class Main
{
public static void main(String args[])
{
Set<Integer> set1 = new HashSet<Integer>();
set1.add(1);
set1.add(8);
set1.add(5);
set1.add(3);
set1.add(0);
System.out.println("set1 before calling remove(): "
+ set1);
boolean removeVal1;
boolean removeVal2;
removeVal1 = set1.remove(150);
removeVal2 = set1.remove(8);
System.out.println("set1 after calling remove(): "
+ set1);
System.out.println("the removal of 8 was: " + removeVal2);
System.out.println("the removal of 150 was: " + removeVal1);
}
}

Explanation

  • Line 8: We declare a Set of integer type: set1. The object is created from the HashSet class. This is because the Set is an interface in Java and, hence, it cannot be instantiated.

  • Lines 9–13: We add the elements into the Set using the Set.add() method.

  • Line 15: We display the Set before calling the remove() method.

  • Lines 19–20: We call the remove() function to remove specific elements from the Set, and assign the returned values to boolean variables. When 150 passes as the argument, nothing happens. This is because it is not present. However, when 8 is removed, the change is reflected.

  • Line 21: We display the Set after calling the remove() method.

  • Lines 23–24: We display the returned values of the remove() method.