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.

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 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.

import java.util.HashSet;
import java.util.Iterator;

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