Skip to content

Latest commit

 

History

History
37 lines (30 loc) · 760 Bytes

File metadata and controls

37 lines (30 loc) · 760 Bytes

Optional Results

Some terminal operations may not find a value. In that case, streams often return Optional instead of null.

Common examples:

  • findFirst()
  • findAny()
  • max()
  • min()

Example

var firstEven = List.of(1, 3, 5, 8, 10).stream()
        .filter(number -> number % 2 == 0)
        .findFirst();

System.out.println(firstEven.orElse(0));

Output

8

Using Optional makes missing values explicit and safer to handle.


Previous: I Single Use Streams.md Next: K When NOT To Use Streams API?.md