Java 8: Find the Max value in a List


We can make use of the Steam API to find the maximum value from a List in Java 8.


Example:
package org.example;

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

public class MaxListValueJava8Example {

    public static void main(String[] args) {

        List<Integer> numbersList = Arrays.asList(2, 10, 8, 12, 9, 5);
        
        OptionalInt maxNumber = numbersList.stream()
                .mapToInt(Integer::intValue)
                .max();

        if (maxNumber.isPresent()) {
            System.out.println("Maximum number is: " + maxNumber.getAsInt());
        } else {
            System.out.println("The provided List is empty!");
        }
    }
}

Output:

Maximum number is: 12

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap