Java Stream min() and max()

In this post, we are going to see Java Stream min() and max() examples. The min() and max() methods in Java Streams are used to find the minimum and maximum element in a stream based on a provided comparator or the natural ordering of elements.

Syntax for min() method

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

Syntax for max() method

Optional<T> max(Comparator<? super T> comparator)
  • T: The type of elements in the stream.
  • comparator: An optional comparator that defines the ordering of elements. If you want to use the natural ordering of elements (e.g., for numbers, strings), you can use Comparator.naturalOrder().


The min() method in Java Streams is used to find the minimum element in a stream based on a provided comparator or the natural ordering of elements. Here is the syntax for the min() method:

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

  • T: The type of elements in the stream.
  • comparator: An optional comparator that defines the ordering of elements. If you want to use the natural ordering of elements (e.g., for numbers, strings), you can use Comparator.naturalOrder().

The Java Streammin() and max() methods returns an Optional<T> that contains the minimum element in the stream according to the specified comparator or natural ordering. If the stream is empty or the comparator finds no minimum element, the Optional will be empty.

Basic example:-

package com.javatute.stream;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class JavaStreamMinMaxExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(10);
        list.add(35);
        list.add(5);
        list.add(33);
        list.add(24);
        list.add(3);
        list.add(20);
        System.out.println("list is:  " + list);

        //First way
        //Integer min = list.stream().min(Integer::compare).get();
        //Second way
        //Integer min = list.stream().min((n1,n2)->n1.compareTo(n2)).get();
        //Third way
        Integer min = list.stream().min(Comparator.naturalOrder()).get();
        System.out.println("min element is:  " + min);
        //First way
        //Integer max = list.stream().max(Integer::compare).get();
        //Second way
        //Integer max = list.stream().max((n1,n2)->n1.compareTo(n2)).get();
        //Third way
        Integer max = list.stream().max(Comparator.naturalOrder()).get();
        System.out.println("max element is:  " + max);

    }
}

Output:-

list is:  [10, 35, 5, 33, 24, 3, 20]
min element is:  3
max element is:  35

Let’s see different examples that demonstrates how to use Java Stream min() and max() methods.

  1. Find the minimum and maximum values in a list of integers.
import java.util.Arrays;
import java.util.List;

public class MinMaxExample1 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);

        Integer min = numbers.stream().min(Integer::compareTo).orElse(null);
        Integer max = numbers.stream().max(Integer::compareTo).orElse(null);

        System.out.println("Min: " + min);
        System.out.println("Max: " + max);
    }
}

Output:

Min: 1
Max: 9
  1. Find the shortest and longest strings in a list of words:
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class MinMaxExample2 {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "fig");

        Optional<String> shortest = words.stream().min((s1, s2) -> s1.length() - s2.length());
        Optional<String> longest = words.stream().max((s1, s2) -> s1.length() - s2.length());

        shortest.ifPresent(s -> System.out.println("Shortest: " + s));
        longest.ifPresent(s -> System.out.println("Longest: " + s));
    }
}

Output:

Shortest: fig
Longest: banana
  1. Find the employee with the lowest and highest salary in a list of employees:
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }
}

public class MinMaxExample3 {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 50000),
            new Employee("Bob", 60000),
            new Employee("Charlie", 75000),
            new Employee("David", 45000)
        );

        Optional<Employee> lowestPaid = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        Optional<Employee> highestPaid = employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));

        lowestPaid.ifPresent(e -> System.out.println("Lowest Paid: " + e.getSalary()));
        highestPaid.ifPresent(e -> System.out.println("Highest Paid: " + e.getSalary()));
    }
}

Output:

Lowest Paid: 45000.0
Highest Paid: 75000.0
  1. Find the oldest and youngest person in a list of persons:
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

public class MinMaxExample4 {
    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
            new Person("Alice", 25),
            new Person("Bob", 30),
            new Person("Charlie", 22),
            new Person("David", 35)
        );

        Optional<Person> oldest = persons.stream().max((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()));
        Optional<Person> youngest = persons.stream().min((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()));

        oldest.ifPresent(p -> System.out.println("Oldest: " + p.getAge()));
        youngest.ifPresent(p -> System.out.println("Youngest: " + p.getAge()));
    }
}

Output:

Oldest: 35
Youngest: 22
  1. Find the product with the lowest and highest price in a list of products:
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public double getPrice() {
        return price;
    }
}

public class MinMaxExample5 {
    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
            new Product("Laptop", 1000),
            new Product("Smartphone", 800),
            new Product("Tablet", 400),
            new Product("Monitor", 300)
        );

        Optional<Product> lowestPriceProduct = products.stream().min((p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()));
        Optional<Product> highestPriceProduct = products.stream().max((p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()));

        lowestPriceProduct.ifPresent(p -> System.out.println("Lowest Price: " + p.getPrice()));
        highestPriceProduct.ifPresent(p -> System.out.println("Highest Price: " + p.getPrice()));
    }
}

Output:

Lowest Price: 300.0
Highest Price: 1000.0

6. Different use cases

import java.util.*;
import java.util.stream.Collectors;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class StreamMinMaxExamples {
    public static void main(String[] args) {
        // Example 1: Finding the minimum and maximum integer in a list
        List<Integer> numbers = Arrays.asList(5, 2, 9, 1, 7, 3);

        Optional<Integer> minNumber = numbers.stream()
                .min(Integer::compareTo);

        Optional<Integer> maxNumber = numbers.stream()
                .max(Integer::compareTo);

        System.out.println("Example 1:");
        System.out.println("Minimum number is: " + minNumber.orElse(0));
        System.out.println("Maximum number is: " + maxNumber.orElse(0));

        // Example 2: Finding the minimum and maximum string length in a list of strings
        List<String> strings = Arrays.asList("apple", "banana", "cherry", "date", "fig");

        Optional<String> shortestString = strings.stream()
                .min(Comparator.comparing(String::length));

        Optional<String> longestString = strings.stream()
                .max(Comparator.comparing(String::length));

        System.out.println("\nExample 2:");
        System.out.println("Shortest string is: " + shortestString.orElse(""));
        System.out.println("Longest string is: " + longestString.orElse(""));

        // Example 3: Finding the youngest and oldest person in a list of custom objects
        List<Person> people = Arrays.asList(
                new Person("Alice", 25),
                new Person("Bob", 30),
                new Person("Charlie", 20)
        );

        Optional<Person> youngestPerson = people.stream()
                .min(Comparator.comparingInt(Person::getAge));

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

        System.out.println("\nExample 3:");
        System.out.println("Youngest person is: " + youngestPerson.orElse(new Person("", 0)));
        System.out.println("Oldest person is: " + oldestPerson.orElse(new Person("", 0)));

        // Example 4: Finding the minimum and maximum of a stream of random integers
        Random random = new Random();
        List<Integer> randomNumbers = random.ints(5, 1, 100)
                .boxed()
                .collect(Collectors.toList());

        Optional<Integer> minRandom = randomNumbers.stream()
                .min(Integer::compareTo);

        Optional<Integer> maxRandom = randomNumbers.stream()
                .max(Integer::compareTo);

        System.out.println("\nExample 4:");
        System.out.println("Minimum random number is: " + minRandom.orElse(0));
        System.out.println("Maximum random number is: " + maxRandom.orElse(0));

        // Example 5: Finding the minimum and maximum using an empty stream
        List<Integer> emptyList = new ArrayList<>();

        Optional<Integer> minEmpty = emptyList.stream()
                .min(Integer::compareTo);

        Optional<Integer> maxEmpty = emptyList.stream()
                .max(Integer::compareTo);

        System.out.println("\nExample 5:");
        System.out.println("Minimum of empty stream is: " + minEmpty.orElse(0));
        System.out.println("Maximum of empty stream is: " + maxEmpty.orElse(0));
    }
}

Output:-

Example 1:
Minimum number is: 1
Maximum number is: 9

Example 2:
Shortest string is: fig
Longest string is: banana

Example 3:
Youngest person is: Person{name='Charlie', age=20}
Oldest person is: Person{name='Bob', age=30}

Example 4:
Minimum random number is: 3
Maximum random number is: 95

Example 5:
Minimum of empty stream is: 0
Maximum of empty stream is: 0

These examples demonstrate how to use Java 8 Stream’s min() and max() methods to find minimum and maximum values in different scenarios.

Test yourself

Question 1: What is the purpose of the min() method in Java 8 Streams?
a) To find the first element in a stream.
b) To find the minimum element in a stream based on a provided comparator.
c) To find the maximum element in a stream based on a provided comparator.
d) To check if any element in the stream matches a given condition.

Question 2: Which of the following statements is true regarding the max() method in Java 8 Streams?
a) It returns the maximum element in the stream based on natural ordering.
b) It returns the minimum element in the stream based on a provided comparator.
c) It returns the maximum element in the stream based on a provided comparator.
d) It returns the sum of all elements in the stream.

Question 3: To use the min() and max() methods, which interface should the elements in the stream implement?
a) Comparable
b) Serializable
c) Cloneable
d) Iterator

Question 4: Which of the following code snippets correctly finds the minimum value in a stream of integers using the min() method?
a)

Optional<Integer> minValue = stream.min(Comparator.comparingInt(Integer::intValue));

b)

Optional<Integer> minValue = stream.min();

c)

int minValue = stream.min(Integer::compareTo).orElse(0);

d)

int minValue = stream.findMin().orElse(0);

Question 5: When using min() or max() on an empty stream, what does it return?
a) A null value
b) An empty optional
c) An exception
d) The first element in the stream

Question 6: Which of the following statements is true about the Comparator passed to min() or max()?
a) It is mandatory; you must always provide a comparator.
b) It is optional; if not provided, natural ordering is used.
c) It is not allowed; you can only use it with primitive data types.
d) It is required only for parallel streams.

Question 7: In the context of min() and max(), what is the purpose of the orElse() method?
a) It is used to specify the order in which elements are compared.
b) It provides a default value to be returned when the stream is empty.
c) It is used to specify a custom comparator.
d) It returns an empty optional if the stream is not empty.

Question 8: Which of the following is true regarding the return type of min() and max() methods?
a) They always return the element itself.
b) They return an Optional containing the element.
c) They return an array of elements.
d) They return a list of elements.

Question 9: What is the time complexity of finding the minimum element in a stream of size N using the min() method?
a) O(1)
b) O(N)
c) O(log N)
d) O(N log N)

Question 10: To use the min() and max() methods, which package should be imported in Java?
a) java.util
b) java.stream
c) java.collection
d) java.streams

Answers:

  1. b) To find the minimum element in a stream based on a provided comparator.
  2. c) It returns the maximum element in the stream based on a provided comparator.
  3. a) Comparable
  4. a) Optional<Integer> minValue = stream.min(Comparator.comparingInt(Integer::intValue));
  5. b) An empty optional
  6. b) It is optional; if not provided, natural ordering is used.
  7. b) It provides a default value to be returned when the stream is empty.
  8. b) They return an Optional containing the element.
  9. b) O(N)
  10. a) java.util

That’s all about Java Stream min() and max() methods.

See docs.

Other Java 8 Stream examples.