Java Stream max() Example

1. Introduction

The max() method in Java Streams is used to find the maximum element according to a given comparator. It is a terminal operation that is often used in data analysis and processing tasks to determine the largest value in a collection of elements.

Key Points

1. max() requires a Comparator to determine how the maximum is calculated.

2. The method returns an Optional to safely handle cases where the stream may be empty.

3. This method can be applied to any type of data element as long as a comparator is provided.

2. Program Steps

1. Import necessary classes.

2. Create a stream of integers.

3. Use max() with an appropriate comparator.

4. Display the result.

3. Code Program

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class StreamMaxExample {

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

        // Using max() with Comparator
        Optional<Integer> maxNumber = numbers.stream().max(Comparator.naturalOrder());

        // Output the result
        maxNumber.ifPresent(max -> System.out.println("The maximum value is: " + max));
    }
}

Output:

The maximum value is: 9

Explanation:

1. A List of Integer is created containing several integers.

2. The max() method is used with Comparator.naturalOrder(), which orders numbers from smallest to largest, thus the max function finds the largest number.

3. max() returns an Optional<Integer>, which is a container object that may or may not contain a non-null value. This use of Optional helps to avoid NullPointerException.

4. The result is printed to the console. If the stream was empty, ifPresent() would prevent any action, thus avoiding errors when trying to access the max value of an empty stream.


Comments