Iterating a collection using Iterator, ListIterator, ForEach and Spliterator

There are several ways to access elements of a Collection.
 
We can simply use a while, do-while or for loop or we can use an iterator.
 
The iterator could be an object implementing Iterator, ListIterator or Spliterator interface.
 
 
spliterator,listiterator and spliterator in java
 
In this article, we will go through the different iterators and see examples of using them.

 

Iterator

 
We can iterate through elements of a collection using Iterator.
 
Here are the steps for using an Iterator:
 
1) Obtain an iterator by using collection’s iterator() method
2) Loop through the elements using iterator’s hasNext() method
3) Obtain the next element by calling next() method.
 

    //Using Iterator to display contents of countries list
    Iterator<String> iter1 = countries.iterator();
    while(iter1.hasNext()){
      String element = iter1.next();
      System.out.print(element + " ");
    }

 
 

ListIterator

 
ListIterator is available only in collections that implement the List interface.
 
A ListIterator gives us the ability to access the collection in either forward or backward direction and lets you modify an element.
 
Otherwise, ListIterator is used like an Iterator.
 

    // Using ListIterator to display contents of countries
  ListIterator<String> iter2 = countries.listIterator();
  while (iter2.hasNext()) {
    String element = iter2.next();
    System.out.print(element + " ");
  }

 
 

For-Each alternative to Iterators

 
If you don’t want to modify the contents of collection or want to obtain the elements in reverse order, the For-Each version is more convenient.
 

  for (String country : countries) {
    System.out.print(country + " ");
  }

 
 

Spliterator

 
JDK 8 introduced the new type of iterator called Spliterator.
 
Spliterator supports parallel programming. But, you can use Spliterator even if you don’t need parallel execution.
 
A Spliterator may traverse elements individually (tryAdvance()) or sequentially in bulk (forEachRemaining()).
 

forEachRemaining(Consumer action)

 
forEachRemaining() method performs the given action for each remaining element, sequentially in the current thread, until all elements have been processed
 

    //Using Spliterator forEachRemaining() to loop through countries list

    Spliterator<String> iter4 = countries.spliterator();
    iter4.forEachRemaining(country -> System.out.print(country + " "));


 

tryAdvance(Consumer action)

 
tryAdvance() method executes an action on the next element in iteration. It returns true, if there is a next element.So, you have do use it in a looping construct.
 

    //Using Spliterator tryAdvance() to loop through countries list

    Spliterator<String> iter3 = countries.spliterator();
    while(iter3.tryAdvance(country -> System.out.print(country + " ")));

 
 
 
Here is a complete example for this :

package com.topjavatutorial;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Spliterator;

public class ArrayListStringDemo {

  public static void main(String[] args) {

    List<String> countries = new ArrayList<String>();
    
    countries.add("Australia");
    countries.add("Canada");
    countries.add("India");
    countries.add("USA");

    System.out.println("Using Iterator to display contents of countries list");
    //Using Iterator to display contents of countries list
    Iterator<String> iter1 = countries.iterator();
    while(iter1.hasNext()){
      String element = iter1.next();
      System.out.print(element + " ");
    }
    
    System.out.println("\n\nUsing ListIterator to modify contents of countries list and display in reverse order");
    
    //Using ListIterator to display contents of countries in reverse order
    ListIterator<String> iter2 = countries.listIterator();
    while(iter2.hasNext()){
      String element = iter2.next();
      iter2.set(element + "1");
    }
    
    //Using ListIterator to display contents of countries in reverse order
    while(iter2.hasPrevious()){
      String element = iter2.previous();
      System.out.print(element + " ");
    }
    
    System.out.println("\n\nUsing For-Each to display contents of countries list");
    for(String country:countries){
      System.out.print(country + " ");
    }
    
    System.out.println("\n\nUsing Spliteror tryAdvance() to loop through countries list");
    //Using Spliterator tryAdvance() to loop through countries list
    Spliterator<String> iter3 = countries.spliterator();
    while(iter3.tryAdvance(country -> System.out.print(country + " ")));
      
    System.out.println("\n\nUsing Spliteror forEachRemaining() to loop through countries list");
    //Using Spliterator forEachRemaining() to loop through countries list
    Spliterator<String> iter4 = countries.spliterator();
    iter4.forEachRemaining(country -> System.out.print(country + " "));
  }

}


 

Here is the output of the above program:
 
Using Iterator to display contents of countries list
Australia Canada India USA

Using ListIterator to modify contents of countries list and display in reverse order
USA1 India1 Canada1 Australia1

Using For-Each to display contents of countries list
Australia1 Canada1 India1 USA1

Using Spliteror tryAdvance() to loop through countries list
Australia1 Canada1 India1 USA1

Using Spliteror forEachRemaining() to loop through countries list
Australia1 Canada1 India1 USA1
 
 

You may also like following articles on Java Collections:

 

 
 

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. […] Iterating a collection using Iterator, ListIterator, ForEach and Spliterator […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: