How to fetch elements with iterator in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 24-Apr-2019 13:51:05
Advertisements