Open In App

How to Create Subsets of a HashSet based on Specific Criteria in Java?

In Java, HashSet provides a dynamic collection of unique elements. Sometimes, we may need to create subsets of a HashSet based on specific criteria.

In this article, we will learn how to create subsets of a HashSet based on Specific Criteria in Java.



Approach Create Subsets of a HashSet based on Specific Criteria

Program to Create Subsets of a HashSet based on Specific Criteria in Java

Below is the Program to Create Subsets of a HashSet based on Specific Criteria:




// Java program to create subsets of a
// HashSet by using Iteration
import java.util.HashSet;
import java.util.Set;
  
public class SubsetExample 
{
    public static void main(String[] args) 
    {
        // Create a HashSet
        Set<String> originalSet = new HashSet<>();
        originalSet.add("Java");
        originalSet.add("Python");
        originalSet.add("C++");
        originalSet.add("JavaScript");
        originalSet.add("Ruby");
  
        // Define criteria 
        int minCharacters = 4;
  
        // Create a new HashSet to store the subset
        Set<String> subset = new HashSet<>();
  
        // Iterate through the original set and add elements
          // that meet the criteria to the subset
        for (String language : originalSet) {
            if (language.length() > minCharacters) {
                subset.add(language);
            }
        }
  
        System.out.println("Subset based on criteria: " + subset);
    }
}

Output

Subset based on criteria: [JavaScript, Python]

Explanation of the above Program:

Note: Customize the criteria and elements in the examples to suit your specific use case.


Article Tags :