Video in progress

What is the difference between findFirst() and findAny()?

findFirst() returns the first element in encounter order. findAny() returns any one of them: in an ordinary stream it is usually the first, but in a parallel one it can be a different one each time. Both return an Optional.

📖 Answer

Optional<User> admin = users.stream()
        .filter(u -> u.role() == Role.ADMIN)
        .findFirst();

On a sequential stream both give practically the same result. The difference shows up on a parallel stream: findFirst waits for other threads' results to preserve order, while findAny takes whichever thread finds one first, which is faster.

Which one when:

  • if "first" matters (the oldest order, the head of a sorted list): findFirst;
  • if it's "is there such an element, give me one": findAny.

Both short-circuit: they stop as soon as they find one and don't look at the rest.

If the element is null, both throw an NPE, because an Optional can't hold null.

If you only need to know whether one exists, write anyMatch(...) instead of filter(...).findFirst().isPresent(): it's easier to read.