0

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...

2

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

And if your code here amounts to someMethod(t), you get to write just thingies.forEach(this::someMethod)
@MarkoTopolnik: Oh very cool! I've added examples and a link to the JLS for that, thanks. (Haven't got into this Java 8 stuff much yet.)
The answer grows and grows in perfectness. :D
1

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)

9 Comments

Strange answer, you are implying he cannot do a for each loop similar to JavaScript in Java < 8?
The user obviously does not want a for loop but a forEach method on a collection
The enhanced for loop (for (Thingy t : collectionOfT)) was added to Java 5 (e.g., many years ago), not Java 8.
@T.J.Crowder Since OP is explicitly asking for a forEach method of the Collection interface, I think this answer fits best. The enhanced for loop also deserves a mention, but this answer fits the question squarely.
He is asking how to perform forEach on a collection, i.e. he is asking how to iterate a collection. Not necessarily a literal method by the name of forEach. That would be my interpretation.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.