In the Article, we will Discuss about the Iterator interface of java. In Java, the Iterator interface is a part of the Java Collections Framework and is used to traverse or iterate over the elements in a collection. It provides a standard way of accessing the elements of a collection without exposing its underlying implementation.
Iterator Interface:
The Iterator interface contains three following methods:
boolean hasNext()Returns true if there are more elements to iterate over in the collection.
E next()Returns the next element in the collection and moves the iterator forward.
void remove()Removes the last element returned by the next() method from the collection.
A common pattern of using the Iterator interface is to use a while loop to iterate over the elements of the collection, calling hasNext() to check if there are more elements and next() to retrieve each element in turn.
Program to Define Functions of Iterator Interface:
// Importing all the required packages
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main{
public static void main(String[] args){
// Create a list of integers
List myList = new ArrayList<>();
// Adding elements to the ArrayList
myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);
// Get an iterator for the list
Iterator iterator = myList.iterator();
// Iterate over the elements of the list using the iterator
while (iterator.hasNext()){
// next function
Integer value = iterator.next();
System.out.println(value);
}
iterator.remove();
}
}
Output:
1
2
3
4
In the above example, we create a list of integers and add four values to it. We then get an Iterator for the list using the iterator() method and use a while loop to iterate over the elements of the list using the hasNext() and next() methods of the Iterator.
When we call hasNext(), the method returns true if there are more elements in the list to iterate over. We then call next() to retrieve the next element in the list, and repeat this process until there are no more elements to iterate over.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment