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
- 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
// 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:
- 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.
Contact Us