Java Program to Remove Elements From HashSet Collection Based on a Specified Predicate

Java program to remove elements from HashSet collection based on a specified predicate

// Java program to remove elements from HashSet collection 
// based on a specified predicate

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.removeIf(val -> (val > 3)))
      System.out.println("Items removed successfully.");
    else
      System.out.println("Unable to remove Items.");

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

Output

Set elements: [1, 2, 3, 4, 5, 6]
Items removed successfully.
Set elements: [1, 2, 3]
Share on:

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

Leave a Comment