Java 8 Program to Find the Maximum Number and Minimum Number in a List

1. Introduction

This blog post will demonstrate how to use Java 8 Streams to find the maximum and minimum numbers in a list. Streams in Java 8 provide a high-level abstraction for processing sequences of elements, including a rich set of operations to perform bulk operations on collections, such as finding the minimum or maximum value.

2. Program Steps

1. Create a list of integers.

2. Use the Stream API to find the maximum and minimum numbers in the list.

3. Display the maximum and minimum numbers found.

3. Java 8 Program to Find the Maximum Number and Minimum Number in a List

import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;

public class MaxMinWithStreams {
    public static void main(String[] args) {
        // Creating a list of integers
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Finding the maximum number using Stream API
        OptionalInt maxNumber = numbers.stream() // Convert list to stream
                                        .mapToInt(Integer::intValue) // Convert Integer to int
                                        .max(); // Find maximum value

        // Finding the minimum number using Stream API
        OptionalInt minNumber = numbers.stream() // Convert list to stream
                                        .mapToInt(Integer::intValue) // Convert Integer to int
                                        .min(); // Find minimum value

        // Displaying the maximum and minimum numbers
        maxNumber.ifPresent(max -> System.out.println("Maximum Number: " + max));
        minNumber.ifPresent(min -> System.out.println("Minimum Number: " + min));
    }
}

Output:

Maximum Number: 10
Minimum Number: 1

Explanation:

1. The program starts by creating a list of integers from 1 to 10.

2. To find the maximum number, the program converts the list to a stream using the stream() method. It then maps each Integer to its int value using mapToInt(Integer::intValue). The max() operation is then called on the stream to find the maximum value, which returns an OptionalInt.

3. Similarly, to find the minimum number, the program uses the same approach but calls the min() operation on the stream.

4. Finally, the program checks if a value is present in the OptionalInt for both maximum and minimum numbers using the ifPresent method and prints the values.

5. This approach using Java 8 Streams makes it easy to find the maximum and minimum values in a collection without manually iterating through the elements.

Comments