A stream contains many elements. With filter we remove elements that do not match a condition. The stream may become shorter.
And on this stream we can use a method like findFirst
to get the first element. We must determine if any elements remain in the stream.
First we use a standard int
array and convert it into a stream with Arrays.stream
. This is an IntStream
instance. Next we use a lambda expression in the filter method.
FindFirst()
returns an OptionalInt
, which may be the first element in the stream (if an element even exists).getAsInt()
method returns the int
represented by the OptionalInt
instance. It must be called only if isPresent
returns true.import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream; public class Program { public static void main(String[] args) { int[] array = { 10, 20, 30, 40, 50, 60 }; // Convert array to Stream. IntStream stream = Arrays.stream(array); // Filter outvalues less than 40. OptionalInt result = stream.filter(value -> value >= 40) .findFirst(); // If a result is present, display it as an int. if (result.isPresent()) { // This is the first value returned by the filter. System.out.println(result.getAsInt()); } } }40
GetAsInt
Methods like getAsInt
must be used in a guard. If we invoke getAsInt
on an OptionalInt
and no element exists, we receive a NoSuchElementException
.
IntStream
. So the OptionalInt
from findFirst
has no value.NoSuchElementException
is thrown. The isPresent
method must be used after findFirst
to be safe.import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream; public class Program { public static void main(String[] args) { int[] array = { -100, -200 }; IntStream stream = Arrays.stream(array); // This filters out all elements. OptionalInt result = stream.filter(value -> value >= 0) .findFirst(); System.out.println(result.getAsInt()); } }Exception in thread "main" java.util.NoSuchElementException: No value present at java.util.OptionalInt.getAsInt(Unknown Source) at Program.main(Program.java:13)
The filter()
method receives an IntPredicate
method on an IntStream
. For other stream types, other predicates are used.
IntStream
is with lambda expressions.Filter receives a lambda that specifies which elements to keep. So it filters out all non-matching elements in a stream.