java foreach
时间: 2023-10-23 08:48:13 浏览: 113
Java forEach is a method that is used to iterate over a collection of elements such as arrays, lists and maps. It is a shorthand for a loop and is used to make the code more concise and readable.
The syntax for using forEach in Java is:
for (elementType element: collection) {
//code block to be executed for each element
}
In the above syntax, the elementType refers to the data type of the elements in the collection and the collection is the variable representing the collection to be iterated over.
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number: numbers) {
System.out.println(number);
}
In the above example, the forEach loop is used to iterate over the array of integers and print each number to the console.
阅读全文