logo

Java - How To Use Iterator?


Show

Frequently, you will desire to cycle during the elements in a compilation. For instance, you might desire to show each constituent. The easiest method to do this is to use an iterator, which is a thing that applies either the Iterator or the ListIterator interface.

Iterator allows you to cycle throughout a set, obtaining or removing constituents. ListIterator expands Iterator to permit bidirectional traversal of an index, and the alteration of elements.

Before you can admission a collection during an iterator, you must find one. Each of the collection groups provides an iterator( ) process that revisits an iterator to the establishment of the collection. By utilizing this iterator object, you can entrée each component in the collection, one part at a time.

In universal, to utilize an iterator to cycle during the contents of a collection, pursue these steps −

  • Find an iterator to the creation of the collection by calling the collection's iterator( ) technique.
  • System a loop that creates a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  • Inside the loop, get each constituent by calling next( ).

For collections that apply List, you can also find an iterator by calling ListIterator.

The Methods Declared by Iterator

Sr.No.Method & Description
1

boolean hasNext( )

Returns true if there are more elements. Otherwise, returns false.

2

Object next( )

Returns the next element. Throws NoSuchElementException if there is not the next element.

3

void remove( )

Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).

The Methods Declared by ListIterator

Sr.No.Method & Description
1

void add(Object obj)

Inserts obj into the list in front of the element that will be returned by the next call to next( ).

2

boolean hasNext( )

Returns true if there is the next element. Otherwise, returns false.

3

boolean hasPrevious( )

Returns true if there is a previous element. Otherwise, returns false.

4

Object next( )

Returns the next element. A NoSuchElementException is thrown if there is not the next element.

5

int nextIndex( )

Returns the index of the next element. If there is not the next element, returns the size of the list.

6

Object previous( )

Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.

7

int previousIndex( )

Returns the index of the previous element. If there is not a previous element, returns -1.

8

void remove( )

Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.

9

void set(Object obj)

Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

Example

Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection.

Of course, ListIterator is available only to those collections that implement the List interface.

import java.util.*;
public class IteratorDemo {

   public static void main(String args[]) {
      // Create an array list
      ArrayList al = new ArrayList();
      
      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");

      // Use iterator to display contents of al
      System.out.print("Original contents of al: ");
      Iterator itr = al.iterator();
      
      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();
      
      // Modify objects being iterated
      ListIterator litr = al.listIterator();
      
      while(litr.hasNext()) {
         Object element = litr.next();
         litr.set(element + "+");
      }
      System.out.print("Modified contents of al: ");
      itr = al.iterator();
      
      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();

      // Now, display the list backwards
      System.out.print("Modified list backwards: ");
      
      while(litr.hasPrevious()) {
         Object element = litr.previous();
         System.out.print(element + " ");
      }
      System.out.println();
   }
}

This will produce the following result −

Output

Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.