Java ListIterator iterate List backward

Introduction

To iterate a List backward via ListIterator in Java

ListIterator<String> litr = al.listIterator();
// Now, display the list backwards. 
while(litr.hasPrevious()) { 
      String element = litr.previous(); 
      System.out.print(element + " "); 
} 
    

Full source

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator; 
 
public class Main { 
  public static void main(String args[]) { 
    // Create an array list. 
    List<String> al = new ArrayList<String>(); 
     //from ww  w  . j  a  v a  2s  .co  m
    // Add elements to the array list. 
    al.add("SQL"); 
    al.add("CSS"); 
    al.add("Java"); 
    al.add("Javascript"); 
    al.add("CSS"); 
    al.add("HTML"); 
    al.add("Demo2s.com");
    al.add("CSS"); 
    al.add(1, "Hi"); 
 
    System.out.println(al);
    
    // Modify objects being iterated. 
    Iterator<String> itr = al.listIterator();
      
    itr = al.iterator();  
    while(itr.hasNext()) { 
      String element = itr.next(); 
      System.out.print(element + " "); 
    } 
    System.out.println(); 
    ListIterator<String> litr = al.listIterator();
    // Now, display the list backwards. 
    while(litr.hasPrevious()) { 
      String element = litr.previous(); 
      System.out.print(element + " "); 
    } 
    System.out.println(); 
  } 
}



PreviousNext

Related