In this tutorial, I will show you all how using Lambda Expression to foreach a List object in Java.
OK, let’s get started!
Usually from Java 7 and earlier, whenever you want to print out elements in a List object, for example:
1 2 3 4 |
List<String> names = new ArrayList<>(); names.add("Khanh"); names.add("Tan"); names.add("Thanh"); |
We usually code as follows:
1 2 3 |
for (int i = 0; i < names.size(); i++) { System.out.println(names.get(i)); } |
or:
1 2 3 |
for (String s : names) { System.out.println(s); } |
Since Java 8, we have several other ways to do this: using the forEach () method in the List object with the Lambda Expression, detail as below:
1 |
names.forEach(s -> System.out.println(s)); |
or with Method reference:
1 |
names.forEach(System.out::println); |
The argument of forEach () method in the List object is the Consumer, a Functional Interface.
Result:
1 2 3 |
Khanh Tan Thanh |