Java 8 Stream came up with methods: count(), max(), min(), findAny(), findFirst(). In this post, we will learn how to use these methods.

Let’s discuss first what these methods are:

count()  This method returns the count of elements of a stream.

max() – This method returns the maximum element of a stream.

min() –  This method returns the minimum element of a stream.

findAny() – This method returns an java.util.Optional describing some element of the stream, or an empty java.util.Optional if the stream is empty.

findFirst() – This method  returns an java.util.Optionaldescribing the first element of this stream, or an empty java.util.Optional if the stream is empty.

Find Count, Max, Min, findAny & findFirst using Java 8 Streams methods...!!! Share on X

Let’s Begin,

Example:

import java.util.ArrayList;
import java.util.List;

public class Java8_Stream_Example {

    public static void main(String[] args) {

        List <Integer> number = new ArrayList <> ();
        number.add(30);
        number.add(20);
        number.add(10);
        number.add(40);

        // Count the numbers
        long count = number.stream()
            .count();
        System.out.println("Total Count: " + count);

        // Max Number
        Integer maxNumber = number.stream()
            .max((x, y) -> x - y)
            .get();
        System.out.println("Max Number: " + maxNumber);

        // Min Number
        Integer minNumber = number.stream()
            .min((x, y) -> x - y)
            .get();
        System.out.println("Min Number: " + minNumber);

        // Find Any Number
        Integer findAnyNumber = number.stream()
            .findAny()
            .get();
        System.out.println("FindAny Number: " + findAnyNumber);

        // Find First number
        Integer findFirstNumber = number.stream()
            .findFirst()
            .get();
        System.out.println("FindFirst Number: " + findFirstNumber);

    }
}

Output:

Total Count: 4
Max Number: 40
Min Number: 10
FindAny Number: 30
FindFirst Number: 30

Find Count, Max, Min, findAny & findFirst using Java 8 Streams methods...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts