Java and Spring Level 1 This level · 90 of 105
Easy java spring

filter then findAny then get finds no match — null or exception?

The 30 second answer

findAny returns an empty Optional, and calling get on that empty Optional throws NoSuchElementException with no value present. It never returns null from the stream. Prefer orElse, orElseGet, orElseThrow with a domain exception, or ifPresent. Also, findAny may return any matching element on a parallel stream, so use findFirst when encounter order matters.

Could you say this in an interview?

findAny() returns an empty Optional; get() throws **NoSuchElementException** ("No value present"). Never null. Use orElse, orElseGet, orElseThrow(() -> new NotFoundException(..)), or ifPresent. Also: findAny may return any element (non-deterministic on parallel streams); use findFirst if order matters.

Sources (2)
  1. Optional.getdocs.oracle.com
  2. Stream.findAnydocs.oracle.com
Previous
Next