Java Stream min() with examples

 202 total views,  2 views today

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

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

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

Method Description

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

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

Java stream min() 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> min = list.stream()
                                    .min((i, j) -> i.compareTo(j));
        System.out.println("min is : " + min.get());
    }
}

Output

min is : 1

Java stream min() 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> min=list
                           .stream()
                           .min(Comparator.comparing(Integer::valueOf));
        System.out.println("min is : " + min.get());
    }
}

Output

min is : 1

Conclusion

min() operation is a terminal operation and it is used for getting the minimum 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!.