Home »
Java »
Java Programs
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 statement
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.
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();
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]
Explanation
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 »