How to iterate over a Java list?


Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.

The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.

Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator() method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.

In general, to use an iterator to cycle through the contents of a collection, follow these steps −

  1. Obtain an iterator to the start of the collection by calling the collection's iterator() method.
  2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
  3. Within the loop, obtain each element by calling next().

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorSample {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      Iterator iterator = list.iterator();
      while(iterator.hasNext()) {
         System.out.println(iterator.next());
      }
   }
}

Output

JavaFx
Java
WebGL
OpenCV

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements