In this article, we will see “How to iterate an Array using forEach statement in Java 8”. Here, we will go through several examples to understand this feature.
Iterate Array using Java 8 forEach...!!! Click To Tweet
Example 1. Array with forEach (Java 8)
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 | import java.util.Arrays; import java.util.function.Consumer; public class ForEach_Java8_Array_Example { public static void main(String[] args) { String[] names = { "noni", "yogi", "dv", "pulkit", "isha", "yashi", "yashu" }; //Anonymous Class Implementation System.out.println("forEach Anonymous Class Implementation:\n"); System.out.println("List names:\n "); Arrays.stream(names).forEach(new Consumer < String > () { @Override public void accept(String v) { System.out.println(v); } }); //Lambda Implementation System.out.println("\nLambda Implementation:\n"); System.out.println("List names: \n"); Arrays.stream(names).forEach((v) -> {System.out.println(v);}); //Method Reference Implementation System.out.println("\nMethod Reference Implementation:\n"); System.out.println("List names: \n"); Arrays.stream(names).forEach(System.out::println); } } |
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 | forEach Anonymous Class Implementation: List names: noni yogi dv pulkit isha yashi yashu Lambda Implementation: List names: noni yogi dv pulkit isha yashi yashu Method Reference Implementation: List names: noni yogi dv pulkit isha yashi yashu |
Example 2. Array with forEach (conditional) (Java 8)
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 | import java.util.Arrays; public class ForEach_Java8_Array_Conditional_Example { public static void main(String[] args) { String[] names = { "noni", "yogi", "dv", "pulkit", "isha", "yashi", "yashu" }; //Array Conditional check System.out.println("Check the array if it contains a person with name 'pulkit':\n"); Arrays.stream(names).forEach((name) -> { if (name.equals("pulkit")) { System.out.println("Expected name 'pulkit' is present in the array"); } }); } } |
1 2 3 | Check the array if it contains a person with name 'pulkit': Expected name 'pulkit' is present in the array |
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams