Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Stream min and max: Finding Extremes

Use Java Stream min and max to find the smallest or largest element, handle empty streams with Optional, and apply custom comparators.

~4 min readJava
#Java Streams#min max#Comparator#Optional
Illustration of a Java stream pipeline with min and max operations extracting the smallest and largest elements from a collection.

When you need the smallest or largest element from a Java Stream, the min and max operations are the direct approach. Both are terminal operations that return an Optional<T> describing the result. This article shows how to use them with natural or custom ordering, how to handle empty streams, and when they are a good fit.

Using min and max on a Stream

The Stream interface defines min(Comparator) and max(Comparator) methods. Each takes a comparator that defines the ordering used to determine the extreme value. The methods return an Optional<T> because the stream might be empty.

java
List<Integer> numbers = List.of(4, 2, 9, 7, 5); Optional<Integer> min = numbers.stream().min(Integer::compareTo); Optional<Integer> max = numbers.stream().max(Integer::compareTo); min.ifPresent(value -> System.out.println("Min: " + value)); max.ifPresent(value -> System.out.println("Max: " + value));

Here, Integer::compareTo is a method reference that provides the natural ordering. The stream processes each element and keeps track of the smallest or largest according to the comparator. Because the operation is terminal, the stream is consumed after calling min or max.

Handling Empty Streams with Optional

The return type Optional<T> exists to handle the case where the stream has no elements. Calling min or max on an empty stream returns an empty Optional, not null or a default value.

java
Stream<String> emptyStream = Stream.empty(); Optional<String> min = emptyStream.min(String::compareTo); System.out.println(min.isEmpty()); // true

You must decide how to handle the empty case. Common approaches include using orElse, orElseThrow, or ifPresent. Avoid calling get() directly without checking, because it throws NoSuchElementException when the optional is empty.

java
int minValue = numbers.stream() .min(Integer::compareTo) .orElse(0); // default when no elements

Custom Comparators for min and max

The default natural ordering works for types that implement Comparable. For other types, or when you need a different ordering, pass a custom comparator.

Consider a Person class with an age field. To find the youngest person:

java
List<Person> people = List.of( new Person("Alice", 30), new Person("Bob", 25), new Person("Charlie", 35) ); Optional<Person> youngest = people.stream() .min(Comparator.comparingInt(Person::getAge));

To get the oldest person, use max with the same comparator:

java
Optional<Person> oldest = people.stream() .max(Comparator.comparingInt(Person::getAge));

For more complex ordering, chain comparators with thenComparing. For example, find the person with the smallest age, and if tied, the one with the lexicographically smallest name:

java
Comparator<Person> byAgeThenName = Comparator.comparingInt(Person::getAge) .thenComparing(Person::getName); Optional<Person> result = people.stream().min(byAgeThenName);

Performance and Intermediate Operations

min and max are not short-circuiting. To determine the result, they must examine every element. The time complexity is O(n) for a sequential stream. For parallel streams, the operation is performed in a reduce-like manner, splitting the work across threads and combining partial results.

Intermediate operations before min or max are evaluated lazily as the terminal operation pulls elements through the pipeline. If you need both the min and max, you have two choices: call each operation on a fresh stream from the same source, or use a collector that computes both in one pass.

java
// Two passes int min = numbers.stream().mapToInt(Integer::intValue).min().orElse(0); int max = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);
java
// One pass with summary statistics IntSummaryStatistics stats = numbers.stream() .mapToInt(Integer::intValue) .summaryStatistics(); int min = stats.getMin(); int max = stats.getMax();

Using IntSummaryStatistics is more efficient when you need both extremes (and possibly sum, average, count) because it processes the stream once. For object streams, you can use Collectors.teeing to compute min and max in a single pass, though it may be overkill for simple cases.

Common Pitfalls with min and max

One frequent mistake is assuming min and max return a default value when the stream is empty. They return an Optional, so forgetting to handle the empty case leads to NoSuchElementException if you call get(). Always use orElse, orElseGet, or orElseThrow.

Another pitfall is using a comparator that is inconsistent with equals. The min and max operations rely on the comparator's ordering. If the comparator returns 0 for elements that are not equal, any of those elements may be returned, so the result is not deterministic. Ensure the comparator is consistent with equality when you need a specific element.

Also, be careful when you use Comparator.naturalOrder() with types that do not implement Comparable. The method's type parameter requires Comparable, so the call normally fails to compile; forcing it with raw types or unchecked casts can lead to a ClassCastException at runtime. Always verify that the element type supports the chosen comparator.

When to Use min and max vs Other Approaches

For small collections, min and max are clear and concise. If you already have a sorted collection, the first or last element might be simpler, but sorting is O(n log n) and unnecessary just to find an extreme. If you need both min and max, consider IntSummaryStatistics for primitive streams or Collectors.teeing for object streams.

For large parallel streams, min and max are efficient because they are implemented as reductions. They are generally preferable to manual reduction with reduce unless you need additional logic.

Example: Finding Min and Max in a List of Objects

Let's combine these concepts in a realistic scenario. Suppose you have a list of transactions and need the smallest and largest amounts that occurred in a specific year.

java
record Transaction(String id, int year, BigDecimal amount) {} List<Transaction> transactions = List.of( new Transaction("T1", 2023, new BigDecimal("120.50")), new Transaction("T2", 2023, new BigDecimal("89.99")), new Transaction("T3", 2024, new BigDecimal("200.00")), new Transaction("T4", 2023, new BigDecimal("150.00")) ); Comparator<Transaction> byAmount = Comparator.comparing(Transaction::amount); Optional<Transaction> min2023 = transactions.stream() .filter(t -> t.year() == 2023) .min(byAmount); Optional<Transaction> max2023 = transactions.stream() .filter(t -> t.year() == 2023) .max(byAmount); min2023.ifPresent(t -> System.out.println("Min amount: " + t.amount())); max2023.ifPresent(t -> System.out.println("Max amount: " + t.amount()));

If the filter leaves no elements, both optionals are empty, and the ifPresent calls do nothing. This is safe and avoids null checks. For a single-pass solution, you could use Collectors.teeing with minBy and maxBy collectors, but the two-pass approach is often simpler and clear enough for moderate-sized lists.

The min and max operations are a core part of the Stream API. They provide a declarative way to find extremes, and with proper handling of Optional and custom comparators, they fit naturally into data processing pipelines. By understanding their behavior on empty streams and their performance implications, you can use them effectively without surprises.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.