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.
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());
Shortest: fig
Longest: banana
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