How to traverse an array using lambda expressions?
You can utilize lambda expressions to iterate through an array by using the forEach() method. Below is an example code of using lambda expressions to traverse an array:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
Arrays.stream(array).forEach(element -> {
// 在此处操作每个元素
System.out.println(element);
});
}
}
In the above example, we used the stream() method of the Arrays class to convert the array into a stream, and then used the forEach() method to iterate through each element. Within the lambda expression, we can perform the desired operation on each element. In this example, we simply print out the value of each element.