Numeric Optional Classes – Streams
By Stephen Trude / September 23, 2023 / No Comments / Certifications of Oracle, Collecting to an Array, Creating an Optional
Numeric Optional Classes
An instance of the generic Optional<T> class can only encapsulate an object. To deal with optional numeric values, the java.util package also defines the following non-generic classes that can encapsulate primitive numeric values: OptionalInt, OptionalLong, and OptionalDouble. For example, an OptionalInt object encapsulates an int value.
The numeric optional classes provide methods analogous to the static factory methods of the Optional class to create a numeric optional from a numeric value and methods to query a numeric optional. The filter(), map(), and flatMap() methods are not defined for the numeric optional classes.
The following methods are defined in the OptionalInt, OptionalLong, and Optional-Double classes in the java.util package. In the methods below, NumType is Int, Long, or Double, and the corresponding numtype is int, long, or double.
static Optional
NumType
empty()
static Optional
NumType
of(numtype value)
These two methods return an empty OptionalNumType instance and an Optional-NumType with the specified value, respectively.
boolean isPresent()
void ifPresent(NumTypeConsumer consumer)
If there is a value present in this Optional, the first method returns true. Otherwise, it returns false.
If a value is present in this Optional, the specified consumer is invoked on the value. Otherwise, it does nothing.
numtype
getAs
NumType
()
If a value is present in this OptionalNumType, the method returns the value. Otherwise, it throws a NoSuchElementException.
numtype
orElse(
numtype
other)
numtype
orElseGet(
NumType
Supplier other)
<X extends Throwable>
numtype
orElseThrow(Supplier<X> exceptionSupplier)
throws X extends Throwable
If a value is present in this OptionalNumType, all three methods return this value.
They differ in their action when there is no value present in this numeric optional. The first method returns the specified other value. The second method invokes the specified other supplier and returns the result. The third method throws an exception that is created by the specified supplier.
Example 16.9 illustrates using numeric optional values. A recipe has an optional number of calories that are modeled using an OptionalInt that can encapsulate an int value. Declaring, creating, and querying OptionalInt objects is analogous to that for Optional objects.
Example 16.9 Using Numerical Optionals
// File: NumericOptionalUsage.java
import java.util.OptionalInt;
class Recipe {
private String recipeName;
private OptionalInt calories; // Optional number of calories.
public String getRecipeName() { return recipeName; }
public OptionalInt getCalories() { return calories; }
public Recipe(String recipeName, OptionalInt calories) {
this.recipeName = recipeName;
this.calories = calories;
}
}
public final class NumericOptionalUsage {
public static void main(String[] args) {
// Creating an OptionalInt:
OptionalInt optNOC0 = OptionalInt.of(3500);
OptionalInt optNOC1 = OptionalInt.empty();
// Creating recipes with optional number of calories:
Recipe recipe0 = new Recipe(“Mahi-mahi”, optNOC0);
Recipe recipe1 = new Recipe(“Loco moco”, optNOC1);
// Querying an Optional:
// System.out.println(recipe1.getCalories()
// .getAsInt()); // NoSuchElementException
System.out.println((recipe1.getCalories().isPresent()
? recipe1.getCalories().getAsInt()
: “Unknown calories.”)); // Unknown calories.
recipe0.getCalories().ifPresent(s -> System.out.println(s + ” calories.”));
System.out.println(recipe0.getCalories().orElse(0) + ” calories.”);
System.out.println(recipe1.getCalories().orElseGet(() -> 0) + ” calories.”);
// int noc = recipe1.getCalories() // RuntimeException
// .orElseThrow(() -> new RuntimeException(“Unknown calories.”));
}
}
Output from the program:
Unknown calories.
3500 calories.
3500 calories.
0 calories.