Java Program: Find max value in List using Java 8 Stream API


Write a program in Java to find the max value in List using Java 8 Stream API

Solution:
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 
 * Program:
 * Find Max Value of List using
 * Java 8 Stream API
 * 
 * Example by Code2care.org
 * 
 */
public class Example {

    public static void main(String[] args) {

        List<Integer> numList = new ArrayList<>();
        numList.add(10);
        numList.add(15);
        numList.add(5);
        numList.add(20);
        numList.add(45);
        numList.add(30);

        Optional<Integer> maxValue = numList.stream().max(Integer::compareTo);

        maxValue.ifPresent(maxVal -> System.out.println("Max value in "+ numList + " is: " + maxVal));

    }
}
Output:

Max value in [10, 15, 5, 20, 45, 30] is: 45

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