1. Introduction

In Java, finding the maximum element in a List is a common task that can be accomplished using the Collections.max() method or Java 8 streams. This post will demonstrate how to find the maximum element in a List using both approaches.

2. Program Steps

1. Import the necessary libraries.

2. Initialize a List of integers.

3. Find the maximum element using the Collections.max() method.

4. Find the maximum element using Java 8 stream’s max() method.

5. Print the results.

3. Code Program

// Step 1: Import the necessary libraries
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class FindMaxInList {

    public static void main(String[] args) {

        // Step 2: Initialize a List of integers
        List<Integer> numbers = Arrays.asList(1, 3, 7, 9, 12, 5);

        // Step 3: Find the maximum element using the Collections.max() method
        Integer maxNumberUsingCollections = Collections.max(numbers);

        // Step 4: Find the maximum element using Java 8 stream’s max() method
        Optional<Integer> maxNumberUsingStream = numbers.stream().max(Integer::compare);

        // Step 5: Print the results
        System.out.println("Maximum number using Collections.max(): " + maxNumberUsingCollections);
        System.out.println("Maximum number using Stream.max(): " + (maxNumberUsingStream.isPresent() ? maxNumberUsingStream.get() : "List is empty"));
    }
}

Output:

Maximum number using Collections.max(): 12
Maximum number using Stream.max(): 12

4. Step By Step Explanation

Step 1: Import the necessary classes and interfaces from Java libraries.

Step 2: Initialize a List of integers with some random values.

Step 3: Use the Collections.max() method to find the maximum element in the list.

Step 4: Use the Java 8 stream’s max() method along with Integer::compare to find the maximum element in the list. The max() method returns an Optional, so we should handle the case where the List is empty.

Step 5: Print the maximum number found using both methods to the console.