Starting Java 8, a new method forEach is introduced to iterate the elements.
This forEach(Consumer<? super T> action) method is created in the following interfaces in java.
- java.lang.Iterable
- java.util.Stream
This method performs a user given action on each element.
In the below example, we can iterate a list of collections with forEach defining a condition.
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 |
import java.util.ArrayList; import java.util.List; public class ForEachExample { public static void main(String args[]) { List numberList = new ArrayList(); numberList.add(1); numberList.add(2); numberList.add(3); numberList.add(4); numberList.add(5); numberList.add(6); numberList.add(7); numberList.add(8); System.out.println("All Numbers"); numberList.forEach((numValue)->{ System.out.println(""+numValue); }); System.out.println("Even Numbers"); numberList.forEach((numValue)->{ if(numValue%2==0) { System.out.println(""+numValue); } }); System.out.println("Stream Filter - Odd Numbers"); numberList.stream() .filter(numValue->(numValue%2==1)) .forEach(System.out::println); } } |
Result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
All Numbers 1 2 3 4 5 6 7 8 Even Numbers 2 4 6 8 Stream Filter - Odd Numbers 1 3 5 7 |