![]() |
VOOZH | about |
The Iterable interface in Java represents a collection of elements that can be traversed one by one. It allows objects to be iterated using an Iterator, making them compatible with the enhanced for-each loop.
public interface Iterable<T>
Here: T represents a generic type parameter in the Iterable interface.
1 2 3 4
Explanation: Here, T is Integer, so the iterable contains integer values and can be used in a for-each loop.
There are three ways in which objects of Iterable can be iterated.
Objects of Classes implementing Collection interface can be iterated using for-each loop, Collection interface extends Iterable interface.
Geeks for Geeks
The forEach() method takes the Lambda Expression as a parameter. This Lambda Expression is called for each element of the collection. In the below example, for each element of the list, the function prints the element to the console.
Geeks for Geeks
We can iterate the elements of Java Iterable by obtaining the Iterator from it using the iterator() method. The methods used while traversing the collections using Iterator to perform the operations are:
Geeks for Geeks
METHOD | DESCRIPTION |
|---|---|
| forEach(Consumer<? super T> action) | Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. |
| iterator() | Returns an iterator over elements of type T. |
| spliterator() | Creates a Spliterator over the elements described by this Iterable. |