This example shows how to iterate a List or ArrayList in Java.
Iterating ArrayList in different ways – Java Example – Iterator, For Loop, For Each Loop and While Loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import java.util.Arrays; import java.util.Iterator; import java.util.List; public class ArrayToList { public static void main(String[] argv) { String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" }; // convert array to list List lList = Arrays.asList(sArray); // iterator loop System.out.println("#1 iterator"); Iterator iterator = lList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // for loop System.out.println("#2 for"); for (int i = 0; i < lList.size(); i++) { System.out.println(lList.get(i)); } // for loop advance System.out.println("#3 for advance"); for (String temp: lList) { System.out.println(temp); } // while loop System.out.println("#4 while"); int j = 0; while (j < lList.size()) { System.out.println(lList.get(j)); j++; } } } |