Skip to Content

Iterate through elements Java ArrayList using ListIterator Example

  1. /*
  2.   Iterate through elements Java ArrayList using ListIterator Example
  3.   This Java Example shows how to iterate through the elements of java
  4.   ArrayList object in forward and backward direction using ListIterator.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.ListIterator;
  9.  
  10. public class IterateThroughArrayListUsingListIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create an ArrayList object
  15.     ArrayList arrayList = new ArrayList();
  16.    
  17.     //Add elements to Arraylist
  18.     arrayList.add("1");
  19.     arrayList.add("2");
  20.     arrayList.add("3");
  21.     arrayList.add("4");
  22.     arrayList.add("5");
  23.    
  24.     /*
  25.       Get a ListIterator object for ArrayList using
  26.       listIterator() method.
  27.     */
  28.     ListIterator itr = arrayList.listIterator();
  29.    
  30.     /*
  31.       Use hasNext() and next() methods of ListIterator to iterate through
  32.       the elements in forward direction.
  33.     */
  34.     System.out.println("Iterating through ArrayList elements in forward
  35.                                                          direction...");
  36.     while(itr.hasNext())
  37.       System.out.println(itr.next());
  38.  
  39.     /*
  40.       Use hasPrevious() and previous() methods of ListIterator to iterate through
  41.       the elements in backward direction.
  42.     */
  43.     System.out.println("Iterating through ArrayList elements in backward
  44.                                                           direction...");
  45.     while(itr.hasPrevious())
  46.       System.out.println(itr.previous());
  47.    
  48.   }
  49. }
  50.  
  51. /*
  52. Output would be
  53. Iterating through ArrayList elements...
  54. Iterating through ArrayList elements in forward direction...
  55. 1
  56. 2
  57. 3
  58. 4
  59. 5
  60. Iterating through ArrayList elements in backward direction...
  61. 5
  62. 4
  63. 3
  64. 2
  65. 1
  66. */