Junior — Middle
Can you prematurely stop a forEach loop inside its body?
sobes.tech AI
Answer from AI
In Kotlin and Java, the standard forEach method does not support early exit from the loop using break or return from the lambda, as it is a higher-order function.
If you need to terminate the loop early, it is better to use a traditional for loop or a for loop with indices:
for (item in collection) {
if (someCondition(item)) {
break // exit the loop early
}
// process item
}
Alternatively, you can use forEach with an exception, but this is not recommended due to reduced readability.
Thus, it is not possible to directly stop a forEach inside its body.