Java List iterate through using while loop, iterator, and for each

Description

Java List iterate through using while loop, iterator, and for each

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<String>();

    list.add("CSS");
    list.add("HTML");
    list.add("Javascript");
    list.add("Java");
    list.add("C++");
    list.add("Java");
    list.add("SQL");

    Iterator<String> iterator = null;

    iterator = list.iterator();//ww w.j  a v a 2s .  c  om
    while (iterator.hasNext()) {
      String element = iterator.next();
      System.out.println(element);
    }

    for (iterator = list.iterator(); iterator.hasNext();) {
      String element = iterator.next();
      System.out.println(element);
    }

    for (String element : list) {
      System.out.println(element);
    }
  }
}



PreviousNext

Related