How to fetch elements with iterator in Java?


Let us first create a List and add elements −

List<String>list = Arrays.asList(new String[] { "P", "Q", "R", "S", "T", "U", "V", "W" });

Now, use Iterator to fetch each element −

Iterator<String>i = list.iterator();

Display the elements −

while (i.hasNext()) {
   System.out.println(i.next());
}

Example

 Live Demo

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Demo {
   public static void main(String[] a) {
      List<String>list = Arrays.asList(new String[] { "P", "Q", "R", "S", "T", "U", "V", "W" });
      Iterator<String>i = list.iterator();
      System.out.println("Displaying elements...");
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

Displaying elements...
P
Q
R
S
T
U
V
W

Updated on: 30-Jul-2019

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements