Iterators in Java provide a way to traverse through collections (like List, Set, Map) and access elements sequentially. They follow the Iterator Design Pattern and are essential for safe collection traversal.
ListIterator<E> - Enhanced iterator for Lists (bidirectional)
Spliterator<E> (Java 8+) - Parallel iteration support
Core Methods
Method
Description
boolean hasNext()
Returns true if more elements exist
E next()
Returns next element
void remove()
Removes current element (optional operation)
2. Using Iterator
Basic Example
List<String>fruits=Arrays.asList("Apple","Banana","Cherry");// Get iteratorIterator<String>it=fruits.iterator();// Traversewhile(it.hasNext()){Stringfruit=it.next();System.out.println(fruit);}
Important Characteristics
Fail-Fast: Throws ConcurrentModificationException if collection is modified during iteration
Single Use: Can't reset - must get new iterator
Universal: Works with all Collection implementations
Iterators provide a standardized way to traverse collections while maintaining encapsulation. Choose the right iterator type based on your needs for safety, directionality, and performance.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)