In Java, objects are stored dynamically using objects. Now in order to traverse across these objects is done using a for-each loop, iterators, and comparators. Here will be discussing iterators. The iterator interface allows visiting elements in containers one by one which indirectly signifies retrieval of elements of the collection in forwarding direction only.
This interface compromises of three methods :
- next()
- hasNext()
- remove()

(A) hasNext() Method
hasNext() method is used to check whether there is any element remaining in the List. This method is a boolean type method that returns only true and false as discussed as it is just used for checking purposes. The hasNext() methods of the Iterator and List Iterator returns true if the collection object over which is used to check during traversal whether the pointing element has the next element. If not it simply returns false. So,
Return Value:
True - if iteration has more elements
False - if iteration has no more elements
Return type: boolean
Example:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add( "Geeks" );
list.add( "for Geeks" );
Iterator<String> iterator = list.iterator();
System.out.println(iterator.hasNext());
iterator.next();
System.out.println(iterator.hasNext());
iterator.next();
System.out.println(iterator.hasNext());
}
}
|
(B) next() method
If there is an element after where hasNext() has returned false on which some execution is to be performed then this method is used to display that element on which execution is supposed to be carried on with help of this method. The next() methods of the Iterator and List Iterator return the next element of the collection. And if there is a need to remove this element remove() method is used.
Return type: Same as collection such as ArrayList, Linked List, etc.
Return value: The next element in the iteration.
Exception: Throws NoSuchElementException if the iteration has no more elements.
Example:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add( "Element1" );
list.add( "Element2" );
list.add( "Element3" );
Iterator<String> iterator = list.iterator();
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());
}
}
|
Output:
Element1
Element2
Element3
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Nov, 2022
Like Article
Save Article