Streams: Collectors.minBy and maxBy return an Optional, not a value

Because the source stream might be empty, minBy and maxBy always collect into an Optional wrapping the extreme element under the given Comparator, rather than the element itself.

Code
List<String> words = List.of("pear", "kiwi", "banana", "fig");
Optional<String> shortest = words.stream()
        .collect(Collectors.minBy(Comparator.comparingInt(String::length)));
Optional<String> longest = words.stream()
        .collect(Collectors.maxBy(Comparator.comparingInt(String::length)));
System.out.println("Shortest: " + shortest.get());
System.out.println("Longest: " + longest.get());
Output
Shortest: fig
Longest: banana
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms