Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Iterable interface in java?
2.1.
Iterator
2.2.
Syntax:
3.
How Java Iterable Works?
4.
How to use an Iterable interface?
5.
Iterable forEach loop
5.1.
Implementation
5.2.
Java
5.3.
Output:
5.4.
Explanation:
6.
Enhanced for loop
6.1.
Implementation:
6.2.
Java
6.3.
Output:
6.4.
Explanation:
7.
Iterator<T> interface
7.1.
Implementation:
7.2.
Java
7.3.
Output:
7.4.
Explanation:
8.
Methods of Iterable
9.
Implementations of Iterable in Java
9.1.
Java
9.2.
Output:
9.3.
Explanation:
10.
Difference between Iterator and Iterable interface in Java
11.
Advantages of Iterable in Java
12.
Disadvantages of Iterable in Java
13.
Limitations of Iterable in Java
14.
Frequently Asked Questions
14.1.
What are the methods in iterable interface?
14.2.
Is Iterable a functional interface in Java?
14.3.
What is iterable and iterator in Java?
15.
Conclusion
Last Updated: May 9, 2024
Easy

Iterable Interface in Java

Author Nagendra
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninjas!! Welcome to another article on Java. Today, we will learn about Iterable Interface in Java. An interface in Java is a blueprint of a class. It describes the behaviour of the class. The interface in java is an abstract data type.

Iterable interface in java

This article explains the details of the Iterable Interface in Java and the difference between the Iterator and the Iterable interface in Java.

Also see, Swap Function in Java

What is Iterable interface in java?

The Iterable interface function in java is used to traverse the collection interface. You can edit, remove or perform any operations on the elements in the collections. 

The iterable method is accessible using java.lang.Iterable package.

Iterator

In Java, an Iterator is an interface that provides a way to access the elements of a collection, one at a time. It allows you to traverse through the collection and perform various operations on its elements, without exposing the underlying implementation of the collection.

The Iterator interface is a part of the Java Collections Framework, and it is used with all the collection classes, such as ArrayList, LinkedList, HashSet, TreeMap, and so on. The Iterator interface provides three methods:

  • hasNext() - This method returns true if the iteration has more elements, false otherwise
  • next() - This method returns the next element in the iteration.
  • remove() - This method removes the last element returned by the Iterator from the underlying collection.

 

Must Read Difference between ArrayList and LinkedList, and Duck Number in Java.

iterator

Syntax:

The syntax of using an Iterator in Java is as follows:

First, you need to obtain an Iterator object for the collection you want to iterate over. You can do this by calling the iterator() method on the collection object, which returns an Iterator object. For example:
 

List<String> myList = new ArrayList<>();
Iterator<String> iterator = myList.iterator();

Once you have obtained an Iterator object, you can use it to iterate over the elements of the collection using a loop. The most common loop to use is a while loop that uses the hasNext() and next() methods of the Iterator to access each element of the collection in turn. For example:


while (iterator.hasNext()) {
   String element = iterator.next();
   // Do something with the element
}

Optionally, you can use the remove() method of the Iterator to remove elements from the collection during iteration. This method removes the last element returned by the next() method from the underlying collection. For example:
 


while (iterator.hasNext()) {
   String element = iterator.next();
   if (someCondition) {
       iterator.remove(); // Remove the element
   }
}

Note that not all collections support the remove() method of the Iterator, and calling it on an unsupported collection will result in an UnsupportedOperationException.

Also read - Jump statement in java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How Java Iterable Works?

In Java, the Iterable interface allows objects to be iterated over using the enhanced for loop. It defines a single method, iterator(), which returns an iterator for traversing elements. This is how it works:

  1. Interface Definition: The Iterable interface is part of the Java Collections Framework and is located in the java.lang package. It defines a single method called iterator().
  2. Iterator Creation: When a class implements the Iterable interface, it must provide an implementation for the iterator() method. This method returns an instance of a class that implements the Iterator interface.
  3. Iterator Usage: The returned iterator is used to traverse the elements of the collection or data structure in a sequential manner. It provides methods like next(), hasNext(), and optionally remove().
  4. Enhanced for Loop: The enhanced for loop in Java, also known as the "for-each" loop, is designed to work with objects that implement the Iterable interface. It simplifies the process of iterating over elements without requiring explicit management of iterators.

How to use an Iterable interface?

You can use the iterable interface in java using the following ways:

 

  • Iterable forEach loop
     
  • Enhanced for loop
     
  • Iterator<T> interface
     

Let's look into the details of each of them.

Iterable forEach loop

The forEach loop traverses the elements of the Iterable interface in Java. It doesn't use any index for accessing elements. It does not provide any means to control the iteration, such as the ability to break or continue the loop.

Implementation

  • Java

Java

import java.util.Vector;
class CodingNinjas {
public static void main(String[] args){
Vector<String> vector = new Vector<String>();
vector.add("Coding");
vector.add("Ninjas");
vector.forEach((item) ->
{ System.out.println(item); });
}
}

Output:

Coding
Ninjas


Explanation:

In the above code snippet, we had defined the vector collection class. We had added two items to it and printed each element using the foreach loop.

Enhanced for loop

The enhanced for loop is the same as the working of forEach loop in Java.  It is a concise and convenient way to iterate over a collection. You can iterate over the items present in the collection using the enhanced for loop. Like, Iterable forEach loop, It doesn't use any index for accessing elements. It does not provide any means to control the iteration.

 Let's understand with a small code snippet and try it on java compiler.

Implementation:

  • Java

Java

import java.util.Vector;

class CodingNinjas {
public static void main(String[] args){
Vector<String> vector = new Vector<String>();
vector.add("Coding");
vector.add("Ninjas");
        for( String item : vector ){
          System.out.println(item);
      }
}
}

Output:

Coding
Ninjas


Explanation:

In the above code snippet, we had defined the vector collection class. We had added two items to it and printed each element using the enhanced for loop.

Also see, Hashcode Method in Java

Iterator<T> interface

You can iterate over the items present in the collection using the Iterator. It allows you to access the elements of a collection one at a time. It provides methods for controlling the iteration. Let's understand with a small code snippet.

Implementation:

  • Java

Java

import java.util.*;
class CodingNinjas {
public static void main(String[] args){
Vector<String> vector = new Vector<String>();
vector.add("Coding");
vector.add("Ninjas");
Iterator<String> iterator = vector.iterator();
    while (iterator.hasNext()) {
        String item = iterator.next();
        System.out.println(item);
        }
}
}

Output:

Coding
Ninjas


Explanation:

In the above code snippet, we had defined the vector collection class. We added two items and printed each element using the Iterator.

Methods of Iterable

MethodDescription
hasNext()Returns true if the iteration has more elements, false otherwise.
next()Returns the next element in the iteration.
remove()Removes the last element returned by the Iterator from the underlying collection.

Implementations of Iterable in Java

  • Java

Java

import java.util.Iterator;

public class MyIterable implements Iterable<String> {

private String[] items;

public MyIterable(String[] items) {
this.items = items;
}

@Override
public Iterator<String> iterator() {
return new MyIterator();
}

private class MyIterator implements Iterator<String> {

private int currentIndex = 0;

@Override
public boolean hasNext() {
return currentIndex < items.length && items[currentIndex] != null;
}

@Override
public String next() {
return items[currentIndex++];
}

@Override
public void remove() {
throw new UnsupportedOperationException();
}
}

public static void main(String[] args) {
String[] items = {"apple", "banana", "orange"};
MyIterable iterable = new MyIterable(items);

for (String item : iterable) {
System.out.println(item);
}
}
}

Output:

apple
banana
orange

Explanation:

In this example, the MyCollection class implements the Iterable interface by providing an implementation for the iterator() method. The iterator() method returns an instance of the MyIterator class, which implements the Iterator interface to traverse the collection of String elements. The MyIterator class provides implementations for the hasNext() and next() methods to iterate over the elements of the collection.

Must Read Type Conversion in Java

Difference between Iterator and Iterable interface in Java

The following table differentiates between the Iterator and Iterable interface in Java.

ParameterIteratorIterable
PurposeUsed to iterate over a collection's elements sequentially.Allows an object to be iterated over using the enhanced for loop or iterators.
Interface TypeInterfaceInterface
Methodsboolean hasNext(): Returns true if the iteration has more elements. <br> E next(): Returns the next element in the iteration. <br> void remove(): Removes the last element returned by the iterator (optional operation).Iterator<T> iterator(): Returns an iterator over the elements in the collection.
UsageObtained from a collection using the iterator() method.Implemented by classes that wish to be able to iterate over their elements.
Role in For-each LoopNot directly used in for-each loops; iterators are used instead.Enables the use of for-each loops directly with objects that implement the Iterable interface.
Example Usagejava <br> List<String> list = new ArrayList<>(); <br> Iterator<String> iterator = list.iterator(); <br> while (iterator.hasNext()) { <br> &nbsp;&nbsp;&nbsp;&nbsp; String element = iterator.next(); <br> &nbsp;&nbsp;&nbsp;&nbsp; System.out.println(element); <br> } <br>java <br> List<String> list = new ArrayList<>(); <br> for (String element : list) { <br> &nbsp;&nbsp;&nbsp;&nbsp; System.out.println(element); <br> } <br>
RelationshipImplements the Iterator interface.Returned by classes that implement the Iterable interface.

Must Read Conditional Statements in Java and What are Loops in Java.

Advantages of Iterable in Java

  • Enhanced for Loop Compatibility: Objects implementing Iterable interface can be directly used with enhanced for loops, simplifying iteration.
  • Standardized Iteration: Provides a standardized way to iterate over collections and custom data structures.
  • Seamless Integration: Enables seamless integration with other Java APIs that rely on iterable objects.
  • Custom Iteration Logic: Allows custom classes to define their own iteration behavior by implementing the iterator() method.
  • Abstraction: Promotes abstraction by separating the logic of iterating over elements from the underlying data structure.

Disadvantages of Iterable in Java

  • Limited Functionality: The Iterable interface only defines a single method (iterator()), limiting the functionality compared to other collection interfaces.
  • Immutable Iterator: Once an iterator is obtained from an iterable object, it cannot modify the underlying collection's structure (e.g., adding or removing elements).
  • Sequential Iteration: Iterable objects generally support sequential iteration, which might not be efficient for certain use cases involving random access or parallel processing.

Limitations of Iterable in Java

  • Single Method Definition: Iterable interface only defines the iterator() method, which might not cover all use cases requiring iteration over elements.
  • Inflexible Iteration Logic: Custom iteration logic defined by classes implementing Iterable is fixed once implemented, limiting adaptability to different iteration requirements.
  • Interface Implementation Overhead: Implementing Iterable interface requires implementing the iterator() method, which might introduce additional overhead in class definitions.

Frequently Asked Questions

What are the methods in iterable interface?

The Iterable interface in Java has only one method, which is the iterator() method. This method returns an Iterator object that can be used to iterate over the elements of the Iterable collection. The Iterator object provides methods such as hasNext() and next() to traverse the collection.

Is Iterable a functional interface in Java?

No, Iterable is not a functional interface in Java. It is a built-in interface that represents a collection of elements that can be iterated over using a for-each loop or an iterator. However, it does not have a single abstract method, which is a requirement for functional interfaces.

What is iterable and iterator in Java?

In Java, the Iterable interface is used to represent a collection of elements that can be iterated over, while the Iterator interface provides a way to iterate over the elements of the collection. By implementing these interfaces, classes can be made iterable, allowing for easy iteration over their elements.

Conclusion

In this article, we have discussed the details of the Iterable Interface in Java and the difference between the Iterator and the Iterable interface in Java.

We hope that the blog has helped you enhance your knowledge regarding Iterable Interface in Java. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews. Do upvote our blogs to help other ninjas grow. Happy Coding!!

Previous article
Break Statement in Java
Next article
Nested If Statements in Java
Live masterclass