Java Iterator - Efficiently Loop Through Collections in Java

Learn how to use the Java Iterator to loop through collections like ArrayList and HashSet. This guide covers the basics of getting an Iterator, accessing elements, and handling collections effectively. Perfect for Java developers looking to optimize data traversal with the Iterator pattern.



Java Iterator

An Iterator is an object used to loop through collections like ArrayList and HashSet. It's named "iterator" because it handles the process of looping.

Getting an Iterator

To use an Iterator, import it from the java.util package and call the iterator() method on your collection:

Syntax

// Import the ArrayList class and the Iterator class
import java.util.ArrayList;
import java.util.Iterator;

public class Main {
public static void main(String[] args) {

// Make a collection
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

// Get the iterator
Iterator<String> it = cars.iterator();

// Print the first item
System.out.println(it.next());
}
}

Output

Output

Volvo

Looping Through a Collection

To iterate through a collection, use hasNext() and next() methods of the Iterator:

Syntax

while(it.hasNext()) {
System.out.println(it.next());
}

Removing Items from a Collection

Iterators allow removing items from a collection while looping. Use the remove() method of the Iterator:

Syntax

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
    Integer i = it.next();
    if(i < 10) {
    it.remove();
    }
}
System.out.println(numbers);
}
}

Output

Output

[12, 23]