The following example explains how to iterate through a List
in various Java versions including Java 8.
package com.smoothexample.java.set;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
populateValues(list);
System.out.println("Using for loop");
for (String s : list) {
System.out.println(s);
}
System.out.println("----------------------------------------------------------------------");
System.out.println("Using ListIterator");
System.out.println("----------------------------------------------------------------------");
Iterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println("----------------------------------------------------------------------");
System.out.println("Using Java8 - Single statement in foreach");
System.out.println("----------------------------------------------------------------------");
list.forEach(name -> System.out.println(name));
System.out.println("----------------------------------------------------------------------");
System.out.println("Using Java8 - multiple statements in foreach");
System.out.println("----------------------------------------------------------------------");
list.forEach(name -> {
String s = "Printing name " + name;
System.out.println(s);
});
}
private static void populateValues(List<String> list) {
for (int i = 1; i <= 10; i++) {
String s = "name" + i;
list.add(s);
}
}
}
Sample output
Using for loop
name6
name5
name4
name3
name9
name10
name8
name7
name2
name1
----------------------------------------------------------------------
Using ListIterator
----------------------------------------------------------------------
name6
name5
name4
name3
name9
name10
name8
name7
name2
name1
----------------------------------------------------------------------
Using Java8 - Single statement in foreach
----------------------------------------------------------------------
name6
name5
name4
name3
name9
name10
name8
name7
name2
name1
----------------------------------------------------------------------
Using Java8 - multiple statements in foreach
----------------------------------------------------------------------
Printing name name6
Printing name name5
Printing name name4
Printing name name3
Printing name name9
Printing name name10
Printing name name8
Printing name name7
Printing name name2
Printing name name1