Stream Optional Value
Description
Some stream operations return optional. For example, the max() method in all stream classes returns an optional object. When using max() method on an empty stream the return value is an optional object with nothing inside.
By using Optional class we can handle the return value from those methods gracefully.
Example
The following code shows how to use Optional object returned form max().
import java.util.OptionalInt;
import java.util.stream.IntStream;
/*from w w w . j a v a 2 s. c o m*/
public class Main {
public static void main(String[] args) {
OptionalInt maxOdd = IntStream.of(10, 20, 30).filter(n -> n % 2 == 1).max();
if (maxOdd.isPresent()) {
int value = maxOdd.getAsInt();
System.out.println("Maximum odd integer is " + value);
} else {
System.out.println("Stream is empty.");
}
}
}
The code above generates the following result.