Open In App

How to use Iterator in Java?

Last Updated : 18 Jul, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.
java.util package has public interface Iterator and contains three methods:

  1. boolean hasNext(): It returns true if Iterator has more element to iterate.
  2. Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.
  3. void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked.




// Java code to illustrate the use of iterator
import java.io.*;
import java.util.*;
  
class Test {
    public static void main(String[] args)
    {
        ArrayList<String> list = new ArrayList<String>();
  
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
  
        // Iterator to traverse the list
        Iterator iterator = list.iterator();
  
        System.out.println("List elements : ");
  
        while (iterator.hasNext())
            System.out.print(iterator.next() + " ");
  
        System.out.println();
    }
}


Output:

List elements : 
A B C D E 

ListIterator

‘ListIterator’ in Java is an Iterator which allows users to traverse Collection in both direction. It contains the following methods:

  1. void add(Object object): It inserts object immediately before the element that is returned by the next( ) function.
  2. boolean hasNext( ): It returns true if the list has a next element.
  3. boolean hasPrevious( ): It returns true if the list has a previous element.
  4. Object next( ): It returns the next element of the list. It throws ‘NoSuchElementException’ if there is no next element in the list.
  5. Object previous( ): It returns the previous element of the list. It throws ‘NoSuchElementException’ if there is no previous element.
  6. void remove( ): It removes the current element from the list. It throws ‘IllegalStateException’ if this function is called before next( ) or previous( ) is invoked.




// Java code to illustrate the use of ListIterator
import java.io.*;
import java.util.*;
  
class Test {
    public static void main(String[] args)
    {
        ArrayList<String> list = new ArrayList<String>();
  
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
  
        // ListIterator to traverse the list
        ListIterator iterator = list.listIterator();
  
        // Traversing the list in forward direction
        System.out.println("Displaying list elements in forward direction : ");
  
        while (iterator.hasNext())
            System.out.print(iterator.next() + " ");
  
        System.out.println();
  
        // Traversing the list in backward direction
        System.out.println("Displaying list elements in backward direction : ");
  
        while (iterator.hasPrevious())
            System.out.print(iterator.previous() + " ");
  
        System.out.println();
    }
}


Output:

Displaying list elements in forward direction : 
A B C D E 
Displaying list elements in backward direction : 
E D C B A 

 
Related Articles:

 



Similar Reads

TreeSet iterator() Method in Java
The Java.util.TreeSet.iterator() method is used to return an iterator of the same elements as that of the TreeSet. The elements are returned in random order from what was present in the Tree set. Syntax: Iterator iterate_value = Tree_Set.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the ele
1 min read
LinkedBlockingDeque iterator() method in Java
The iterator() method of LinkedBlockingDeque returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a "weakly consistent" iterator. Syntax: public Iterator iterator() Parameters: This method does not accept any parameter. Returns: Th
2 min read
IntStream iterator() in Java
IntStream iterator() returns an iterator for the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : PrimitiveIterator.OfInt iterator() Where, PrimitiveIterator.OfInt is an Iterator specialized for int values. Return Value : IntStream iterator() returns the element itera
2 min read
Java AbstractSequentialList | iterator() method
AbstractSequentialList iterator() method in Java is used to get an Iterator or List Iterator over a list. It returns an iterator over the elements in this list (in proper sequence). This method overrides iterator() in class AbstractList&lt;E&gt; Syntax: public Iterator&lt;E&gt; iterator() Return Value: This method returns an iterator over the eleme
2 min read
Java | Implementing Iterator and Iterable Interface
Iterators are used in Collection framework in Java to retrieve elements one by one. For more details and introduction related to this, see this link. Why it is needed to implement Iterable interface? Every class that implements Iterable interface appropriately, can be used in the enhanced For loop (for-each loop). The need to implement the Iterator
4 min read
HashSet iterator() Method in Java
The Java.util.HashSet.iterator() method is used to return an iterator of the same elements as the hash set. The elements are returned in random order from what present in the hash set. Syntax: Iterator iterate_value = Hash_Set.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the elements of th
1 min read
PriorityQueue iterator() Method in Java
The Java.util.PriorityQueue.iterator() method is used to return an iterator of the same elements as the Priority Queue. The elements are returned in random order from what present in the Queue. Syntax: Iterator iterate_value = Priority_Queue.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the
2 min read
LinkedBlockingQueue iterator() method in Java
The iterator() method of LinkedBlockingQueue returns an iterator of the same elements, as this LinkedBlockingQueue, in a proper sequence. The elements returned from this method contains all the elements in order from first(head) to last(tail) of LinkedBlockingQueue. The returned iterator is weakly consistent.Syntax: public Iterator&lt;E&gt; iterato
3 min read
ArrayDeque iterator() Method in Java
The Java.util.ArrayDeque.iterator() method is used to return an iterator of the elements of the ArrayDeque. Syntax: Iterator iterate_value = Array_Deque.iterator(); Parameters: The method does not take any parameter. Return Value: The method iterates over the elements of the deque and returns the values(iterator). Below programs illustrate the Java
2 min read
Iterator vs Collection in Java
Iterator and Collection, both has helped and comforted the programmers at many a times. But their usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iteratorIterators are used in Collection framework in Java to retrieve elements one by one. M
3 min read
Article Tags :
Practice Tags :