Remove single element from a HashSet in Java


To remove a single element from a HashSet, use the remove() method.

First, create a HashSet −

HashSet hs = new HashSet();

Now, add elements to the HashSet −

hs.add("R");
hs.add("S");
hs.add("T");
hs.add("V");
hs.add("W");
hs.add("Y");
hs.add("Z");

Let us now remove an element −

hs.remove("R");

The following is an example to remove a single element from a HashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("R");
      hs.add("S");
      hs.add("T");
      hs.add("V");
      hs.add("W");
      hs.add("Y");
      hs.add("Z");
      System.out.println(hs);
      // removing a single element
      hs.remove("R");
      System.out.println(hs);
      // removing another element
      hs.remove("W");
      System.out.println(hs);
   }
}

Output

[R, S, T, V, W, Y, Z]
[S, T, V, W, Y, Z]
[S, T, V, Y, Z]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

911 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements