How to Create Subsets of a HashSet based on Specific Criteria in Java?
Last Updated :
20 Feb, 2024
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
- Iterate through the original HashSet.
- Define the criteria for selecting elements.
- Create a new HashSet to store the subset.
- Add elements that meet the criteria to the new subset.
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
import java.util.HashSet;
import java.util.Set;
public class SubsetExample
{
public static void main(String[] args)
{
Set<String> originalSet = new HashSet<>();
originalSet.add( "Java" );
originalSet.add( "Python" );
originalSet.add( "C++" );
originalSet.add( "JavaScript" );
originalSet.add( "Ruby" );
int minCharacters = 4 ;
Set<String> subset = new HashSet<>();
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:
- This Java program creates subsets of a HashSet by iterating over its elements.
- Then it adds those elements to meet a specified criteria to a new HashSet.
- In this example, the criteria are to include only elements with a length greater than a specified minimum number of characters.
- At last, it prints the subset based on the criteria.
Note: Customize the criteria and elements in the examples to suit your specific use case.
Share your thoughts in the comments
Please Login to comment...