How do I iterate LinkedList elements using ListIterator?

This example show you how to use the ListIterator interface to iterate elements of a LinkedList.

package org.kodejava.util;

import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;

public class LinkedListListIterator {
    public static void main(String[] args) {
        List<String> grades = new LinkedList<>();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");

        // Retrieves object from LinkedList using the ListIterator
        // interface.
        ListIterator<String> iterator = grades.listIterator();
        while (iterator.hasNext()) {
            System.out.println("Grades: " + iterator.next());
            System.out.println("  hasPrevious  : " + iterator.hasPrevious());
            System.out.println("  hasNext      : " + iterator.hasNext());
            System.out.println("  previousIndex: " + iterator.previousIndex());
            System.out.println("  nextIndex    : " + iterator.nextIndex());
        }
    }
}

The program will print the following output:

Grades: A
  hasPrevious  : true
  hasNext      : true
  previousIndex: 0
  nextIndex    : 1
Grades: B
  hasPrevious  : true
  hasNext      : true
  previousIndex: 1
  nextIndex    : 2
Grades: C
  hasPrevious  : true
  hasNext      : true
  previousIndex: 2
  nextIndex    : 3
Grades: D
  hasPrevious  : true
  hasNext      : true
  previousIndex: 3
  nextIndex    : 4
Grades: E
  hasPrevious  : true
  hasNext      : false
  previousIndex: 4
  nextIndex    : 5
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.