Best practice for iterating through an iterable until either a condition is met or the iterable has been fully iterated over in Java

Viewed 47

Sorry if title isn't super clear. I have two ways to do this where: c is an iterable of Objects

boolean condition = false;
for (Object o : c) {
    if (meetsCondition(o)) {
        condition = true;
        break;
    }
}
boolean condition = false;
Iterator<Object> iter = c.iterator();
while (!condition && iter.hasNext()) if (meetsCondition(iter.next())) condition = true;

If Object o meets a condition that is described using the method meetsCondition() then I would like to update the result and stop looping as the program only requires one of the objects to meet this condition.

Unsure as to what is the best practice as have been informed that using break is not good practice.

Thank you.

2 Answers

There are many more ways to achieve that. I prefer "streams", which would look like this:

var condition = c.stream()
   .takeUntil(this::meetsCondition)
   .findAny()
   .isPresent();

Many "senior devs" are more familiar with your first solution. Because Streams are very new.
If I had the chance to choose between your solutions, I would take the first one.
The second example is very complex and hard to read.

Edit

As suggested in the comments (thanks Dawood ibn Kareem), it can be just:

var condition = c.stream()
   .anyMatch(this::meetsCondition);

Something in the lines of:

c.stream()
  .filter(o -> meetsCondition(o)) // Find the appropriate values
  .findAny() // Take any object
  .ifPresent(o -> doSomething(o)); // If there is an object do something with it.
Related