I am a Javascript developer and I starting to check out Java.
One question that I have is how I can perform forEach on a collection. I can't seem to find any such method in Java collections...
I am a Javascript developer and I starting to check out Java.
One question that I have is how I can perform forEach on a collection. I can't seem to find any such method in Java collections...
Since Java 5, you can use the enhanced for
loop for this. Assume you have (say) a List<Thingy>
in the variable thingies
. The enhanced for
loop looks like this:
for (Thingy t : thingies) {
// ...
}
As of Java 8, there's an actual forEach
method on iterables that accepts a lambda function:
thingies.forEach((Thingy t) -> { /* ...your code here... */ });
If you have an existing method you want to use, you can use a method reference instead of an inline lambda:
thingies.forEach(this::someMethod); // Instance method on `this`
thingies.forEach(SomeClass::someMethod); // Static method on `SomeClass`
thingies.forEach(foo::someMethod); // Instance method on `foo` instance
What you are trying to accomplish can only be done in a form similar to JavaScript, in Java 8 or newer. Java 8 added the forEach (defender) method on Iterable (for which Collection inherits)