Java Stream max() with examples

 210 total views,  2 views today

Welcome to Java 8 series. In this tutorial, you will learn about java stream min() with examples.

max() is a part of the Stream pipeline and terminal operation. It belongs to the Stream interface.

max () operation allows us to get the maximum value available in the stream of elements. Once max() is invoked on a stream, it returns the maximum value of the stream and the stream will be closed. We cannot reuse the stream as we have invoked a terminal operation i.e., maximum().

Method Description

Optional<T> max(Comparator<? super T> comparator)

Returns the maximum element of this stream according to the provided Comparator.

Let us now see a few examples of Java 8 stream max()

Java stream max() operation example

public class StaticReference
{
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        Optional<Integer> max = list.stream()
                                    .max((i, j) -> i.compareTo(j));
        System.out.println("max is : " + max.get());
    }
}

Output

max is : 7

Java stream max() operation using Comparator example

public class StaticReference
{
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        
        Optional<Integer> max=list.stream()
                        .max(Comparator.comparing(Integer::valueOf));
        System.out.println("max is : " + max.get());
    }
}

Output

max is : 7

Conclusion

max() operation is a terminal operation and it is used for getting the maximum element in the stream.

References : Official documentation

Thanks for reading. Please a comment and give us a thumbs up! 

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.