Trusted answers to developer questions

Iterable vs. ​ Iterator

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

An iterable is a collection of objects that can be traversed. The objects are traversed using an iterator that uses particular methods to iterate over an object.

How an iterator is initialized

Java

Iterator<Integer> iterator =
Arrays.asList(1,2,3).iterator();

Python

iterator = iter(1,2,3) 

How an iterator traverses

Java

An iterator uses the following methods to traverse objects in Java:

  • hasNext()
  • next()
  • forEachRemaining() (this can only be used in Java 8)

Python

An iterator uses the following methods to traverse objects in Python:

  • next(): returns the next item in the iterable.
  • iter(): returns the iterator object itself.
svg viewer

Code

The codes below explain the relationship between the iterable and iterator:

import java.util.*;
import java.util.*;
import java.util.Arrays;
import java.util.List;
class example {
public static void main( String args[] ) {
System.out.println("Printing done using hasNext() and next()");
Iterator<Integer> myObj =
Arrays.asList(1, 2, 3).iterator();
while (myObj.hasNext()){
System.out.println(myObj.next());
}
}
}

RELATED TAGS

iterator
iterable
vs.
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?