Java Stream min() Example

1. Introduction

The min() method in Java Streams is used to find the smallest element according to a specified comparator. It is crucial for data analysis, sorting algorithms, or any scenario where determining the minimum value is required.

Key Points

1. min() is a terminal operation that returns an Optional to account for potentially empty streams.

2. It requires a Comparator to define the "minimum" based on specific criteria.

3. This method is widely applicable across various data types and collections.

2. Program Steps

1. Import necessary classes.

2. Create a stream of elements.

3. Apply the min() method with a 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 StreamMinExample {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(10, 3, 7, 0, -1, 8);

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

        // Output the result
        minNumber.ifPresent(min -> System.out.println("The minimum value is: " + min));
    }
}

Output:

The minimum value is: -1

Explanation:

1. A List of Integer is created with both positive and negative integers.

2. The min() method is applied to the stream created from the list. Comparator.naturalOrder() is used to define natural ordering among integers (from smallest to largest), thus finding the minimum.

3. min() returns an Optional<Integer>, which is used here to safely handle the scenario where the list could be empty. Using ifPresent(), the program only attempts to print the minimum value if it exists, preventing any exceptions that would arise from attempting to access a value from an empty Optional.

4. The output clearly shows -1 as the minimum value, demonstrating that the method effectively identifies the smallest number in the list according to natural ordering.


Comments