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.Optional
describing 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...!!! Click To Tweet
Let’s Begin,
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <span style="font-size: 16px;">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); } }</span> |
Output:
1 2 3 4 5 6 | <span style="font-size: 16px;">Total Count: 4 Max Number: 40 Min Number: 10 FindAny Number: 30 FindFirst Number: 30 </span> |
Find Count, Max, Min, findAny & findFirst using Java 8 Streams methods...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts: