In the example, we use Arrays.stream() method to transform the array into a stream. The forEach() method then iterates over the elements and prints them to the console.
Java 8 forEach() Array Example
package net.javaguides.corejava.java8.foreach; import java.util.Arrays; public class ForEachArray { public static void main(String[] args) { int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Arrays.stream(nums).forEach(System.out::println); String[] fruits = { "Banana", "Apple", "Orange" }; Arrays.stream(fruits).forEach(System.out::println); } }
Output:
1 2 3 4 5 6 7 8 9 Banana Apple Orange
Comments
Post a Comment