I know the meaning of foreach
in programming and when to use it. Is there a foreach
keyword in Java? I tried to find a list of keywords but there is only for
and not foreach
.
Foreach is a loop statement in the Perl programming language that executes once for each value of a data object. It takes the general form: foreach thing (in object) { do something; do something else; }
JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse the array or collection elements. The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
The foreach statement: enumerates the elements of a collection and executes its body for each element of the collection. The do statement: conditionally executes its body one or more times.
As of Java 1.8, Java now has a foreach loop ...
package org.galarik.arick;
import java.util.ArrayList;
import java.util.List;
public class ExampleForEach {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
strings.add("Mom");
strings.add("Dad");
strings.add("Dad's Java");
strings.add("Mom's Java");
// Original for loop
int stringsSize = strings.size();
Object[] oldStrings = strings.toArray();
for(int stringIndex = 0; stringIndex < stringsSize; ++stringIndex ) {
System.out.println("Original Content: " + oldStrings[stringIndex]);
}
// For loop, as of Jova 1.5
for (String string : strings) {
System.out.println("All Content: " + string);
}
// forEach loop as of Java 1.8
strings.stream().forEach((string) -> {
System.out.println("For Content: " + string);
});
// Using forEach loop to do a filter
strings.parallelStream().filter(someString -> someString.contains("Java"))
.forEach((someOtherString) -> {
System.out.println("Content With Java: " + someOtherString);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With