Java Stream max() Example

In this tutorial, we will learn Java 8 Stream max() terminal operation with an example.

The Java Stream max() method is a terminal operation that returns the largest element in the Stream.

Java Stream max() Example

Here is a Java Stream max() example:

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args)
    {
        List<String> stringList = new ArrayList<>();

        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        stringList.add("one");

        Stream<String> stream = stringList.stream();

        Optional<String> max = stream.max((val1, val2) -> {
            return val1.compareTo(val2);
        });

        String maxString = max.get();

        System.out.println(maxString);
    }
}

Output:

two

Java Stream Methods/APIs Examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments