Remove specified element from HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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

First, declare a HashSet and add elements −

Set<Integer> hs = new HashSet<Integer>();
hs.add(20);
hs.add(39);
hs.add(67);
hs.add(79);
hs.add(81);
hs.add(87);
hs.add(88);

Let’s say you need to remove element 39. For that, use the remove() method −

hs.remove(39);

The following is an example to remove specified element from HashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      Set<Integer> hs = new HashSet<Integer>();
      hs.add(20);
      hs.add(39);
      hs.add(67);
      hs.add(79);
      hs.add(81);
      hs.add(87);
      hs.add(88);
      System.out.println("Elements = "+hs);
      // remove specific elements
      hs.remove(39);
      System.out.println("Updated Elements = "+hs);
   }
}

Output

Elements = [81, 67, 20, 39, 87, 88, 79]
Updated Elements = [81, 67, 20, 87, 88, 79]
raja
Published on 10-Jan-2019 09:38:25
Advertisements