Retrieving Elements from Collection in Java- ListIterator

Java 8Server Side ProgrammingProgramming

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.

raja
Published on 14-Sep-2020 13:09:05
Advertisements