C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Lambda: The lambda in this program returns true if the element is greater than or equal to 40. Otherwise it returns false.
LambdaFindFirst: This returns an OptionalInt, which may be the first element in the stream (if an element even exists).
GetAsInt: This method returns the int represented by the OptionalInt instance. It must be called only if isPresent returns true.
Java program that uses filter, findFirst
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());
}
}
}
Output
40
Here: The filter call removes all elements from the IntStream. So the OptionalInt from findFirst has no value.
Result: The NoSuchElementException is thrown. The isPresent method must be used after findFirst to be safe.
Java program that causes NoSuchElementException
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());
}
}
Output
Exception in thread "main" java.util.NoSuchElementException:
No value present
at java.util.OptionalInt.getAsInt(Unknown Source)
at Program.main(Program.java:13)
Tip: The easiest way to specify arguments like IntStream is with lambda expressions.