Retrieve Elements from Collection Using ListIterator in Java



Following is an example to retrieve elements from Collection in Java-ListIterator −

Example

 Live Demo

import java. util.* ;
public class Demo {
   public static void main(String args[]) {
      Vector<Integer> my_vect = new Vector<Integer>();
      my_vect.add(56);
      my_vect.add(78);
      my_vect.add(98);
      my_vect.add(34);
      ListIterator my_iter = my_vect.listIterator();
      System.out.println("In forward direction:");
      while (my_iter.hasNext())
      System.out.print(my_iter.next()+" ") ;
      System.out.print("\n\nIn backward direction:\n") ;
      while (my_iter.hasPrevious())
         System.out.print(my_iter.previous()+" ");
   }
}

Output

In forward direction:
56 78 98 34
In backward direction:
34 98 78 56

A class named Demo contains the main function, where a Vector instance is defined. Elements are added to the vector with the help of the ‘add’ function. Now, a ListIterator instance is created, and the elements of the vector are printed on the screen. The elements of the vector are also printed in a reversed direction with the help of the ‘hasPrevious’ and ‘previous’ functions.

Updated on: 2020-09-14T09:39:05+05:30

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements