Java Program to Remove an Item From HashSet Collection

You are currently viewing Java Program to Remove an Item From HashSet Collection

Java program to remove an item from HashSet collection

// Java program to remove an item from 
// HashSet collection

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashSet < Integer > nums = new HashSet();

    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);
    nums.add(5);
    nums.add(6);

    System.out.println("Set elements: " + nums);

    if (nums.remove(5)) //return true on successful removal.
      System.out.println("Item 5 removed from 'nums' Set successfully.");
    else
      System.out.println("Item 5 is not removed from 'nums' Set.");

    System.out.println("Set elements after removing item 5: " + nums);
  }
}

Output

Set elements: [1, 2, 3, 4, 5, 6]
Item 5 removed from 'nums' Set successfully.
Set elements after removing item 5: [1, 2, 3, 4, 6]

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply