beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – LinkedList ListIterator example

By Chaitanya Singh | Filed Under: Java Collections

In this example we will see how to iterate a LinkedList using ListIterator. Using Listterator we can iterate the list in both the directions(forward and backward). Along with traversing, we can also modify the list during iteration, and obtain the iterator’s current position in the list. Read more about it at ListIterator javadoc.

Example

Here we have a LinkedList of Strings and we are traversing it in both the directions using LitIterator.

import java.util.LinkedList;
import java.util.ListIterator;
public class ListIteratorExample {
 
 public static void main(String[] args) {
 
    // Create a LinkedList
    LinkedList<String> linkedlist = new LinkedList<String>();
 
    // Add elements to LinkedList
    linkedlist.add("Delhi");
    linkedlist.add("Agra");
    linkedlist.add("Mysore");
    linkedlist.add("Chennai");
    linkedlist.add("Pune");
 
    // Obtaining ListIterator
    ListIterator listIt = linkedlist.listIterator();
 
    // Iterating the list in forward direction
    System.out.println("Forward iteration:");
    while(listIt.hasNext()){
       System.out.println(listIt.next());
    }

    // Iterating the list in backward direction
    System.out.println("\nBackward iteration:");
    while(listIt.hasPrevious()){
       System.out.println(listIt.previous());
    } 
 }
}

Output:

Forward iteration:
Delhi
Agra
Mysore
Chennai
Pune

Backward iteration:
Pune
Chennai
Mysore
Agra
Delhi

Enjoyed this post? Try these related posts

  1. Hashtable Iterator example – Java
  2. Java ArrayList trimToSize() Method example
  3. How to synchronize HashMap in Java with example
  4. Java – Get element from specific index of LinkedList example
  5. Java – Add element at specific index in LinkedList example
  6. Replace Vector elements using index – Java example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap