How to perform forEach loop in Java -
i javascript developer , starting check out java.
one question have how can perform foreach on collection. can't seem find such method in java collections...
since java 5, can use enhanced for
loop this. assume have (say) list<thingy>
in variable thingies
. enhanced for
loop looks this:
for (thingy t : thingies) { // ... }
as of java 8, there's actual foreach
method on iterables accepts lambda function:
thingies.foreach((thingy t) -> { /* ...your code here... */ });
if have existing method want use, can use method reference instead of 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
Comments
Post a Comment