How to find the maximum value from an Integer using the stream in Java 8?

By | March 23, 2023

To find the maximum value from a collection of Integer objects using Java 8 streams, you can use the max method which is provided by the Stream interface. Here’s an example:

List<Integer> numbers = Arrays.asList(1, 5, 3, 9, 4);

Optional<Integer> maxNumber = numbers.stream().max(Integer::compare);

if (maxNumber.isPresent()) {

    System.out.println(“Maximum number is ” + maxNumber.get());

} else {

    System.out.println(“List is empty”);

}

In the above example, we first create a list of Integer objects. We then call the stream method on the list to create a stream of integers. Next, we call the max method on the stream, passing in Integer::compare as a comparator function to compare integers. The max method returns an Optional containing the maximum value in the stream, which we can then access using the get method.

Note that the max method returns an Optional because the stream may be empty. In the example above, we check whether the Optional contains a value by calling the isPresent method on it, and print the maximum value if it does. If the Optional is empty, we print a message indicating that the list is empty.

Leave a Reply

Your email address will not be published. Required fields are marked *