Remove specified element from HashSet in Java


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]

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements