Iterator and Iterable in Java — Java Stories
✦ Introduction:
In the realm of Java programming, navigating through collections of objects is a common task, and the Iterable and Iterator interfaces play a pivotal role in this process. These interfaces provide a standardized way to traverse and manipulate elements within a collection, making code more readable, efficient, and maintainable. Let’s dive deep into programming prospects of Iterable and Iterator.
Understanding Iterable and Iterator Interfaces:
▸ Iterable
The Iterable interface acts as a root interface for all collection classes in Java. It defines a single method, iterator(), which allows objects to be iterated using the enhanced for-loop (foreach loop) or manually with an Iterator object. By implementing Iterable, a class signals that it can provide an iterator to iterate over its elements.
To enable iteration over instances of a custom class, it should implement the Iterable interface and provide an implementation for the iterator() method.
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
// Implementation
}
default Spliterator<T> spliterator() {
// Implementation
}
}▸ Iterator
The Iterator interface provides a uniform way to iterate over elements of a collection, regardless of its specific implementation (e.g., ArrayList, HashSet). It allows sequential access to elements and supports methods like next(), hasNext(), and optionally remove().
For user-defined classes, we need to implement custom logic to ensure that these objects can be iterated using next() and hasNext() methods. In addition to supporting the next() method for iterations, implementing Iterable enables custom objects to be iterated over using an enhanced for-each loop.
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}✦ Practical Example of Using Iterator and Iterable
package dev.neelesh.iterinng;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorPractical {
static StudentLinkedList sl1;
class StudentLinkedList implements Iterable<StudentLinkedList>{
String name;
StudentLinkedList next;
public StudentLinkedList(String name) {
this.name = name;
this.next = null;
}
public StudentLinkedList(String name, StudentLinkedList next) {
this.name = name;
this.next = next;
}
@Override
public Iterator<StudentLinkedList> iterator() {
return new Iterator<>() {
StudentLinkedList current = StudentLinkedList.this;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public StudentLinkedList next() {
StudentLinkedList temp = current;
current = current.next;
return temp;
}
};
}
@Override
public String toString() {
return "StudentLinkedList{" +
"name='" + name + '\'' +
", next=" + next +
'}';
}
}
static {
IteratorPractical ip = new IteratorPractical();
StudentLinkedList sl5 = ip.new StudentLinkedList("Neelesh");
StudentLinkedList sl4 = ip.new StudentLinkedList("Araf", sl5);
StudentLinkedList sl3 = ip.new StudentLinkedList("Syam", sl4);
StudentLinkedList sl2 = ip.new StudentLinkedList("Swapnika", sl3);
sl1 = ip.new StudentLinkedList("Sandhya", sl2);
}
public static void main(String[] args) {
Iterator<StudentLinkedList> iterator = sl1.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5));
Iterator<Integer> itr = list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}✦ Code Explanation
- StudentLinkedList Inner Class (
Iterable<StudentLinkedList>)
- Purpose: Represents a custom class representing a singly linked list where each node (
StudentLinkedList) contains a name and a reference to the next node. - Iterable Implementation: Implements the
Iterable<StudentLinkedList>interface, allowing instances to be iterated using Java'sfor-eachloop andnext()method. iterator()Method: Provides a custom iterator that sequentially traverses through the linked list:
1.hasNext(): Checks if there is a next node (current != null). 2.next(): Returns the current node (temp), then moves to the next node (current = current.next).
2. Static Initialization Block (static { ... })
- Purpose: Initializes a static instance (
sl1) ofStudentLinkedListin the outer class (IteratorPractical). - Usage: Creates instances of
StudentLinkedList(sl2tosl5) and links them together to form a linked list structure (sl1).
3. main Method
Get Neelesh Janga’s stories in your inbox
Join Medium for free to get updates from this writer.
Usage of Custom Iterator (sl1.iterator()):
- Obtains an iterator (
iterator) forsl1. - Iterates through
sl1using awhileloop: - Uses
iterator.hasNext()to check for the next node. - Uses
iterator.next()to retrieve and print each node.
Usage of Standard Iterator (list.iterator())
- Creates an
ArrayList(list) initialized with integers. - Obtains an iterator (
itr) forlist. - Iterates through
listusing awhileloop: - Uses
itr.hasNext()to check for the next integer. - Uses
itr.next()to retrieve and print each integer.
Note:
Iterable interface though being technically accepted as a functional interface but its not, here is how:
While Iterable has a single abstract method, it is not considered a functional interface because its design and intent are to provide iteration over a collection rather than represent a “single abstract operation/behaviour”.Now, what is single abstract behaviour?
The term “single abstract behavior” refers to the core functionality that a functional interface in Java is intended to represent.
Example: Comparator to compare 2 values, Predicate to get boolean result based on the method logic, etc.While Iterable has one abstract method (iterator), it is not designed to represent a single, concise operation or behavior. Instead, it represents a collection that can be iterated over, which is a BROADER CONCEPT.
Resources
Social Accounts
- LinkedIn — https://www.linkedin.com/in/neelesh-janga/
- GitHub — https://github.com/Neelesh-Janga










