Quantcast
Viewing latest article 6
Browse Latest Browse All 30

Answer by Du-Lacoste for In detail, how does the 'for each' loop work in Java?

Using older Java versions, including Java 7, you can use a foreach loop as follows.

List<String> items = new ArrayList<>();items.add("A");items.add("B");items.add("C");items.add("D");items.add("E");for(String item : items) {    System.out.println(item);}

The following is the very latest way of using a for each loop in Java 8 (loop a List with forEach+ lambda expression or method reference).

Lambda

// Output: A,B,C,D,Eitems.forEach(item->System.out.println(item));

Method reference

// Output: A,B,C,D,Eitems.forEach(System.out::println);

For more information, refer to "Java 8 forEach examples".


Viewing latest article 6
Browse Latest Browse All 30

Trending Articles