Get startedGet started for free

Filtering large numbers

In many applications, filtering data is an essential step in processing large datasets. For example, in financial applications, age-restricted platforms, or performance tracking systems, you may need to remove values above a certain threshold. In this exercise, you will practice using an Iterator to traverse a collection and remove numbers greater than 25, ensuring it has only relevant values.

All the necessary classes from java.util have been imported for you.

This exercise is part of the course

Input/Output and Streams in Java

View Course

Exercise instructions

  • Create an Iterator for the created set numbers.
  • Use a while loop to check if the set numbers has more elements.
  • Retrieve the next element and assign to a new variable current.
  • If the number is greater than 25, remove it.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class NumberFilter {
    public static void main(String[] args) {
        HashSet numbers = new HashSet<>();

        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);

        // Create a new Iterator object
        Iterator it = numbers.____();
        
        // Check if more elements exist
        while (it.____()) {
        	// Retrieve next element
        	int current = it.____();
            if (current > 25) {
            	// Remove the retrieved element
                it.____();
            }
        }

        System.out.println(numbers);
    }
}
Edit and Run Code