Remove single element from a HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 16-Jan-2019 11:47:03
Advertisements