Iterable is a generic interface that represents elements which can be iterated. It resides in java.lang package and was introduced in 1.5 version. It contains iterator() method that is mandatory to implement by its implementing classes, otherwise objects of that very classes can’t be used within for-each loop.
Syntax
interface Iterable<T> {}
T represents object type required for iteration.
Further, the interface consists an abstract method that return iterator object.
Iterator<T> iterator( )
Iterator method provides three methods, one abstract and two default methods. These are the following :
- Iterator<T> iterator() : It returns iterator object of element type T
- default void forEach(Consumer action) : forEach() traverses each element one by one until all the elements in the iterable are processessed. It accepts consumer which signifies it would takes each element one by one and perform some operation on it without returning anything.
- default Spliterator<T> spliterator(): It creates and returns spliterator for iterable elements.
Iterator Interface in Java
Collection interface extends Iterable interface which signifies all its implementing classes must required to implement its abstract methods in collection framework. In Iterable interface, there is a single abstract method named iterator method that returns an iterator object which is responsible for traversing collection objects. Basically, it is a replacement of Enumeration which is used prior to Collection framework. It provides three methods namely, hasNext(), remove(), foreEachRemaning() and next().
All the implementing classes, such as Arraylist, LinkedList, HashSet, provide implementation for the iterator() which returns its corresponding object.
In the below example, ArrayList collection indirectly implements iterable interface. As a result, it implements the method.
Syntax:
ArrayList<String> employeeNames = new ArrayList<>(); employeeNames.iterator();
There are 4 methods supported by iterator
- next() : It returns next element that comes immediately after current pointing object in the collection
- hasNext() : It checks whether the collection is having more elements to traverse or not
- remove(): It removes an object returned by next() from a collection
- forEachRemaining(Consumer<? super E> action): It iterates over all the elements and perform action on the respective elements
How Java Iterable Interface Works with Program Example?
All the collection or iterable implementing classes, ranging from ArrayList to LinkedHashSet, provide method definition of iterator().
Iterator provides certain methods that are used to traverse over the collection objects. For instance, hasNext() is used to check whether a collection consists more elements or not and next() method is used for retrieving object from the collection.
Java program to iterate over elements of a collection using iterator
public class IteratorExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); Iterator<String> itr; names.add("John"); names.add("Jay"); names.add("Kakarot"); names.add("Micky"); itr = names.iterator(); while(itr.hasNext()) // while the collection consists object, do { String name = itr.next(); // returns single object from the collection System.out.println("Element :: "+ name); // printing name from the collection } }
Output:
Element :: John Element :: Jay Element :: Kakarot Element :: Micky
Java Program to show the working of forEachRemaining() in iterator
Program:
public class IteratorExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); Iterator<String> itr; names.add("John"); names.add("Jay"); names.add("Kakarot"); names.add("Micky"); itr = names.iterator(); itr.forEachRemaining(System.out::println); // the method iterates, fetches single element from the collection and perform the given logic in the Consumer (Feature of Java 8) } }
Output:
John Jay Kakarot Micky
There are 4 ways an iterable object can be iterated
1. Enhanced for loop or forEach loop
2. forEach Loop
3. Iterator Object
4. splitIterator
Enhanced For Loop
It is also known as for-each loop, introduced in Java 5. It provides functionality to iterate through a collection of objects.It executes the loop body until all the elements are traversed.
Unlike traditional for loop, it doesn’t provide any control on loop execution as it would always iterate till last element of the collection.
Since, it’s a control statement, not an interface or object. Therefore, there is no privilege for updation, deletion or removal operation in it. It can only iterate through collections.
Java program to iterate a collection of objects using for each or enhanced for loop
Program:
public class IteratorExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("John"); names.add("Jay"); names.add("Kakarot"); names.add("Micky"); for (String name: names) { System.out.println("Elements :: "+ name); } } }
forEach() in Java
forEach is an efficent way to iterate through a collection. It is a default method of iterable which is the root interface in collection hierarchy. Is is added in Java 8 that accepts a lambda expression which takes a single input, performs some action or logic and returns nothing.
It is used to iterate through collection objects, similar, to enhanced for loop.
Java program to iterate over collection objects using forEach method of iterable interface
Program:
public class IteratorExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("John"); names.add("Jay"); names.add("Kakarot"); names.add("Micky"); names.forEach(name -> System.out.println("Elements :: "+ name)); } }
Output:
Elements :: John Elements :: Jay Elements :: Kakarot Elements :: Micky
Java program to demonstrate iteration using iterator object
There are two ways to traverse through iterator object
- Using hasNext() and next() method
Program:
public class IteratorExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); Iterator<String> itr; names.add("Firang"); names.add("Jason"); itr = names.iterator(); while(itr.hasNext()) // while the collection consists object, do { String name = itr.next(); // returns single object from the collection System.out.println("Element :: "+ name); // printing name from the collection } } }
Output:
Element :: Firang Element :: Jason
2. Using forEachRemaining() method
Program:
public class IteratorExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); Iterator<String> itr; names.add("Firang"); names.add("Jason"); itr = names.iterator(); itr.forEachRemaining(System.out::println); } }
Output:
Firang Jason
SplitIterator in Java
In iterable interface, there is another method that returns SplitIterator object named splitIterator() to iterate over elements of collection. It can traverse elements not only in sequential manner but also in parallel manner.
Program:
public class IteratorExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); Spliterator<String> itr ; names.add("Firang"); names.add("Jason"); itr = names.spliterator(); itr.forEachRemaining(System.out::println); } }
Output:
Firang Jason
Difference between iterable and iteraor in Java?
Basis | Iterable | Iterator |
---|---|---|
Definition | It is the root interface of collection hierarchy that signifies objects that can be iterated | It is an interface that provides methods to iterate through elements of collection one by one |
Implementation | iterator() required to be implemented by implementation class | next(), hasNext() needs to be implemented by implementation class |
Preserves state | It doesn't preserves iteration state | It preserves iteration state |
Operations | It can only read elements of collection | It can read and remove elements of collection |
Purpose | Its instance can initialize a new iterator instance each time when its method called | Its instance provides utility methods such as hasNext(), next() which maintain the iteration state |
Methods | It supports 3 methods i.e. iterator(), spliterator() and forEach() | It supports 4 methods next(), hasNext(), remove(), foreachRemaining(). |
Traversal direction | Iterable supports single directional traversal | Iterator's child interfaces i.e ListIterator supports bio-directional traversal |
Package | It resides within java.lang.iterable | It resides within java.util.iterator |