ListIterator Example In Java

 Posted On  | Yashwant Chavan 

ListIterator extended from Iterator interface and it allow to traverse a list bidirectional. You can use next() and previous() methods to traverse forward and backward direction. In below example we will iterate elements using ListIterator interface in both direction (forward and backward).

There are couple of other methods which will provide you current iterating element index position.

  • previousIndex() - Returns the index of the element that would be returned by a subsequent call to previous().
  • nextIndex() - Returns the index of the element that would be returned by a subsequent call to next().

ListIterator Example

package com.technicalkeeda.app;

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

public class ListIteratorExample {

    public static void main(String a[]) {

        List cities = new ArrayList();

        cities.add("Pune");
        cities.add("Nashik");
        cities.add("Mumbai");

        ListIterator listIterator = cities.listIterator();

        System.out.println("---------------Forward Directiton-----------------");

        while (listIterator.hasNext()) {
            System.out.println("Index - " + listIterator.nextIndex() + " City Name - " + listIterator.next());
        }

        System.out.println("-------------Backward Directiton-----------------");

        while (listIterator.hasPrevious()) {
            System.out.println("Index - " + listIterator.previousIndex() + " City Name - " + listIterator.previous());
        }
    }

}

Output

---------------Forward Directiton-----------------
Index - 0 City Name - Pune
Index - 1 City Name - Nashik
Index - 2 City Name - Mumbai
-------------Backward Directiton-----------------
Index - 2 City Name - Mumbai
Index - 1 City Name - Nashik
Index - 0 City Name - Pune


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0300 seconds.