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

Given a HashSet, we have to remove elements based on a specified predicate.
Submitted by Nidhi, on May 11, 2022

Problem Solution:

In this program, we will create a set using the HashSet collection to store integer elements. Then we will remove items from the HashSet collection using the removeIf() method.

Program/Source Code:

The source code to remove elements from the HashSet collection based on specified predicate is given below. The given program is compiled and executed successfully.

// 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();


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

    if (nums.removeIf(val -> (val > 3)))
      System.out.println("Items removed successfully.");
      System.out.println("Unable to remove Items.");

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


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


In the above program, we imported the "java.util.*" package to use the HashSet collection. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. Here, we created a set nums to store integer data elements using HashSet collection. Then we removed elements from set nums based on a specific predicate using the removeIf() method and printed the updated HashSet. The removeIf() method returns true on successful removal, otherwise, it returns false.

Java HashSet Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.