Java HashSet remove() Method Tutorial

In this section, we will learn what the HashSet remove() method is and how to use it in Java.

What is Java HashSet remove() Method?

The Java HashSet remove() method is used to remove an element from a HashSet object.

Java HashSet remove() Method Syntax:

public boolean remove(Object o)

remove() Method Parameters:

The method takes one argument and that is the object we want to remove from the target HashSet object.

remove() Method Return Value:

The return value of this method is of type Boolean.

The value will be true, if the element (the argument) was removed from the target HashSet object. Otherwise, the value false will return instead.

remove() Method Exceptions:

The method does not throw an exception.

Example: using HashSet remove() method

import java.util.HashSet; 
public class Main {

    public static void main(String[] args){
      HashSet<Integer> set = new HashSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);
      set.add(5);
      set.add(6);
      set.add(7);

      set.remove(1);
      set.remove(3);
      set.remove(5);

      for (int i: set){
         System.out.println(i);
      }
    }
}

Output:

2

4

6

7
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies