VOOZH about

URL: https://www.geeksforgeeks.org/java/iterable-interface-in-java/

⇱ Iterable Interface in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iterable Interface in Java

Last Updated : 31 Mar, 2026

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.

  • Introduced in JDK 1.5 and part of java.lang package
  • Provides iterator(), spliterator(), and forEach() methods
  • Enables use of enhanced for-each loop

Declaration Syntax

public interface Iterable<T>

Here: T represents a generic type parameter in the Iterable interface.


Output
1
2
3
4

Explanation: Here, T is Integer, so the iterable contains integer values and can be used in a for-each loop.

Ways of Iterating

There are three ways in which objects of Iterable can be iterated.

Using enhanced for loop

Objects of Classes implementing Collection interface can be iterated using for-each loop, Collection interface extends Iterable interface.


Output
Geeks
for
Geeks

Using forEach loop

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.


Output
Geeks
for
Geeks

Using Iterator

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:

  • hasNext(): It returns false if we have reached the end of the collection, otherwise returns true.
  • next(): Returns the next element in a collection.
  • remove(): Removes the last element returned by the iterator from the collection.
  • forEachRemaining(): Performs the given action for each remaining element in a collection, in sequential order.

Output
Geeks
for
Geeks

Methods of Iterable

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.

Related topics


Comment
Article Tags: