Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Collection framework → Iterator

Collection framework

Iterator

Iterators

Iterators are a cornerstone of working with collections in Java. They provide a standardized way to traverse elements within a collection, one at a time. Here's a breakdown of iterators with examples:

What is an Iterator?

An iterator acts like a cursor that points to elements in a collection. It follows the Iterator interface in the java.util package, defining essential methods hasNext(): Checks if there's another element in the collection. Returns true if there are more elements, false otherwise. next(): Returns the element the iterator is currently pointing to and advances the cursor to the next element. Throws a NoSuchElementException if there are no more elements. remove() (optional): Removes the element that was most recently returned by next(). Not all iterators support this method. Using Iterators with Examples: Here's an example to use an iterator to iterate through an ArrayList of names:
Iterator example in java collections import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String[] args) { // Create an ArrayList of names ArrayList<String> names = new ArrayList<>(); names.add("Tutorials"); names.add("Box"); names.add("Com"); // Get an iterator from the ArrayList Iterator<String> iterator = names.iterator(); // Loop through elements using hasNext() and next() while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); } } }

Output

Tutorials Box Com
This code iterates through the names list and prints each name. The hasNext() check ensures we don't try to access non-existent elements.

Benefits of Iterators:

Safety: Iterators prevent accidental modification of the underlying collection during iteration through hasNext() and next(). This safeguards against unexpected behavior. Flexibility: Iterators work with various collection types (List, Set, etc.) as long as they implement the Iterable interface (most collections do). This promotes code reusability. Fail-Fast behavior: Most Java iterators follow the "fail-fast" principle. If the underlying collection is modified during iteration (except through the iterator's remove() method), a ConcurrentModificationException is thrown. This helps detect potential issues during development. Important Considerations: Removing elements: Use remove() cautiously. It typically removes the element most recently returned by next(). Modifying the collection structure through remove() might invalidate the iterator. Concurrent modifications: Avoid modifying the collection you're iterating over through other means while using an iterator. This can lead to unpredictable behavior.

Example: Using remove() with an Iterator:

Example to use remove() method with an iterator
iterator & remove() in java collections import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String[] args) { ArrayList names = new ArrayList<>(); names.add("Tutorials"); names.add("Box"); names.add("Com"); Iterator iterator = names.iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (name.equals("Com")) { iterator.remove(); // Remove "Com" from the list } else { System.out.println(name); } } System.out.println(names); } }

Output

Tutorials Box [Tutorials, Box]
This code iterates through the list, removes "Box" using remove(), and prints the remaining elements. Remember to use remove() with caution to avoid unexpected behavior.

Tutorials