When working with collections in Java, it’s often necessary to traverse through elements to perform some operations. One of the most common ways to do this is by using Iterators. An Iterator is an object in Java that allows you to loop through elements of a collection, such as a List
, Set
, or Queue
. It provides a simple, unified way to iterate over various data structures without exposing the underlying implementation.
An Iterator is an interface in Java that provides methods to traverse through a collection. It allows access to the elements of a collection in a sequential manner. With an Iterator, you can perform the following actions:
- Access elements in a collection
- Check if there are more elements left to access
- Remove elements during iteration
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import java.util.ArrayList; import java.util.Iterator; public class IteratorOperationsExample { public static void main(String[] args) { // Creating a list of integers ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); numbers.add(50); // Creating an iterator to traverse the list Iterator<Integer> iterator = numbers.iterator(); // Iterating through the list using iterator while (iterator.hasNext()) { Integer currentNumber = iterator.next(); // Get the current element // Print the current element System.out.println("Current Number: " + currentNumber); // Removing the element if it equals 30 if (currentNumber == 30) { iterator.remove(); // Removes 30 from the list System.out.println("Removed Number: " + currentNumber); } } // Displaying the modified list System.out.println("Modified List: " + numbers); } } //Output Current Number: 10 Current Number: 20 Current Number: 30 Removed Number: 30 Current Number: 40 Current Number: 50 Modified List: [10, 20, 40, 50] |
hasNext()
: Before accessing the next element, we check if there are more elements in the collection usingiterator.hasNext()
.next()
: We useiterator.next()
to retrieve the current element in the iteration.remove()
: When the current number is 30, we useiterator.remove()
to remove it from the list.
Why Use Iterators?
- Uniformity: Iterators provide a consistent way of iterating over different types of collections, whether you’re working with a
List
,Set
, orQueue
. - Safety: Using the
remove()
method via the iterator is safer than using theremove()
method of the collection itself during iteration, as it avoidsConcurrentModificationException
. - Flexibility: Iterators can be used with both static and dynamic collections, and they abstract away the underlying details of how elements are stored.