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


The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet.

  • The program defines a class called RemoveEle_HashSet. Inside the RemoveEle_HashSet class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input.
  • Within the main method, a HashSet called nums is created and initialized with Integer objects. The HashSet represents a set of numbers.
  • After initializing nums with some elements using the add() method, the program proceeds to demonstrate the usage of the removeIf() method.
  • The removeIf() method is called on the nums HashSet and takes a lambda expression as an argument. The lambda expression (val -> (val > 5)) represents a predicate that returns true if the value is greater than 5.
  • The removeIf() method removes all elements from the HashSet that satisfy the given predicate. In this case, all elements greater than 5 will be removed.
  • If any elements are removed, the program prints "Items removed successfully." Otherwise, it prints "Unable to remove Items."
  • Finally, the program prints the updated elements of the HashSet using the System.out.println() statement.

Source Code

import java.util.*;
public class RemoveEle_HashSet
{
	public static void main(String[] args)
	{
		HashSet <Integer> nums = new HashSet<Integer>();
		nums.add(1);
		nums.add(2);
		nums.add(3);
		nums.add(4);
		nums.add(5);
		nums.add(6);
		nums.add(7);
		nums.add(8);
		nums.add(9);
		nums.add(10);
 
		System.out.println("HashSet Elements : " + nums);
 
		if (nums.removeIf(val -> (val > 5)))
		{		
			System.out.println("Items removed successfully.");
		}
		else
		{
			System.out.println("Unable to remove Items.");
		}
		System.out.println("HashSet Elements : " + nums);
	}
}

Output

HashSet Elements : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Items removed successfully.
HashSet Elements : [1, 2, 3, 4, 5]

Example Programs