MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Input/Output and Streams in Java

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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 dan Jalankan Kode