Course contentsShow
← Java
Lesson 1525 of 2,87033. Streams API: Terminal OperationsFree lesson

Finding Minimum Elements with min(Comparator)

Use min() to find the smallest element in a stream by providing a Comparator for comparison logic.

Finding Minimum Elements with min(Comparator)

You'll learn how to extract the smallest element from a stream by supplying custom comparison logic.

When you need to find the minimum value in a stream, the min() terminal operation is your tool. Unlike count() which simply tallies elements, min() must compare them to determine which is smallest. Since "smallest" isn't always obvious (smallest by age? by price? alphabetically?), you provide a Comparator that defines your comparison rules.

How min() Works

The min() method returns an Optional because the stream might be empty—there's no minimum of nothing! When the stream contains elements, min() uses your Comparator to repeatedly compare pairs until it identifies the smallest one.

Signature: Optional<T> min(Comparator<? super T> comparator)

Basic Usage

List<Integer> numbers = List.of(5, 2, 8, 1, 9);
Optional<Integer> smallest = numbers.stream()
    .min(Integer::compareTo);

smallest.ifPresent(System.out::println); // Prints: 1

With Custom Objects

List<String> words = List.of("apple", "pie", "a");
Optional<String> shortest = words.stream()
    .min(Comparator.comparingInt(String::length));

shortest.ifPresent(System.out::println); // Prints: "a"

Here, we're not finding the alphabetically first word—we're finding the shortest by length.

Handling Empty Streams

Optional<Integer> result = Stream.<Integer>empty()
    .min(Integer::compareTo);

System.out.println(result.isPresent()); // false

The Optional wrapper protects you from null pointer exceptions when no minimum exists.

Key Takeaway:
Use min(Comparator) to find the smallest stream element according to custom comparison logic; it returns an Optional to safely handle empty streams.