HashSet remove(Object o) method in java

Let’s learn HashSet remove(Object o) method in java.

HashSet remove(Object o) method in java

remove(Object o) method of HashSet class removes the specified element from this set if it is present.

Returns true if this set contained the element.

Syntax:

public boolean remove(Object o)

Parameters:

o object to be removed from this set, if present.

Returns:

true if the set contained the specified element.

Also read – HashSet in java

Now let’s see example on HashSet remove(Object o) method.

import java.util.HashSet;
public class HashSetRemoveObjectMethodExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("hello");
      hs.add("world");
      hs.add("java");
      System.out.println("HashSet before using remove(Object o) method: " + hs);
      // remove string "world" from HashSet
      boolean bool = hs.remove("world");
      System.out.println("Has string removed? " + bool);
      System.out.println("HashSet after using remove(Object o) method: " + hs);
   }
}


Output:

HashSet before using remove(Object o) method: [world, java, hello]
Has string removed? true
HashSet after using remove(Object o) method: [java, hello]

1 Comment

Comments are closed.