Java Reference
In-Depth Information
The Optional<T> class describes a non-null reference type value or its absence. The java.util package contains
three more classes named OptionalInt , OptionalLong , and OptionalDouble to deal with optional primitive values.
They contain similarly named methods that apply to primitive data types, except for getting their values. They do not
contain a get() method. To return their values, the OptionalInt class contains a getAsInt() , the OptionalLong class
contains a getAsLong (), and the OptionalDouble class contains a getAsDouble() method. Like the get() method of
the Optional class, the getters for primitive optional classes also throw a NoSuchElementException when they are
empty. Unlike the Optional class, they do not contain an ofNullable() factory method because primitive values
cannot be null . The following snippet of code shows how to use the OptionalInt class:
// Create an empty OptionalInt
OptionalInt empty = OptionalInt.empty();
// Use an OptionaInt to store 287
OptionalInt number = OptionalInt.of(287);
if(number.isPresent()){
int value = number.getAsInt();
System.out.println("Number is " + value);
}
else {
System.out.println("Number is absent.");
}
Number is 287
Several methods in the Streams API return an instance of the Optional , OptionalInt , OptionalLong , and
OptionalDouble when they do not have anything to return. For example, all types of streams let you compute the
maximum element in the stream. If the stream is empty, there is no maximum element. Note that in a stream pipeline,
you may start with a non-empty stream and end up with an empty stream because of filtering or other operations
such as limit, skip, etc. For this reason, the max() method in all stream classes returns an optional object. The program
in Listing 13-5 shows how to get the maximum integer from IntStream .
Listing 13-5. Working with Optional Values
// OptionalTest.java
package com.jdojo.streams;
import java.util.Comparator;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class OptionalTest {
public static void main(String[] args) {
// Get the maximum of odd integers from the stream
OptionalInt maxOdd = IntStream.of(10, 20, 30)
.filter(n -> n % 2 == 1)
.max();
 
Search WWH ::




Custom Search