Sub topic 11
Primitive Optionals
You already know that Optional<T> holds an object that may or may not be there. Java also has three smaller cousins for plain numbers: OptionalInt, OptionalLong, and OptionalDouble. This chapter shows what they are, why they exist, and how to read a value out of them.
What a primitive is
A primitive is one of Java's built-in basic value types, such as int, long, or double. A primitive is not an object, so it cannot go inside a generic type like Optional<T> directly.
You can write Optional<Integer>. Integer is a wrapper class, which is an object that holds one int. Wrapping every number in an object takes extra memory and extra work. This step is called boxing.
The primitive Optionals skip the boxing. An OptionalInt holds a plain int or holds nothing.
| Class | Holds | Read the value with |
|---|---|---|
| `OptionalInt` | an `int` | `getAsInt()` |
| `OptionalLong` | a `long` | `getAsLong()` |
| `OptionalDouble` | a `double` | `getAsDouble()` |
Where you meet them
You will rarely create these yourself. They usually come from primitive streams, which are streams of plain numbers: IntStream, LongStream, and DoubleStream. Operations such as max, min, and average return a primitive Optional, because an empty stream has no maximum and no average.
A worked example
This program creates primitive Optionals directly and gets them from streams. It then reads each one safely.
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class PrimitiveDemo {
public static void main(String[] args) {
OptionalInt three = OptionalInt.of(3);
OptionalInt none = OptionalInt.empty();
System.out.println(three.getAsInt()); // 3
System.out.println(none.isPresent()); // false
System.out.println(none.orElse(0)); // 0
OptionalDouble avg = IntStream.of(2, 4, 9).average();
System.out.println(avg.getAsDouble()); // 5.0
OptionalLong smallest = LongStream.of(40L, 7L, 12L).min();
smallest.ifPresent(n -> System.out.println("Min: " + n)); // Min: 7
OptionalDouble noAvg = IntStream.empty().average();
System.out.println(noAvg.orElseGet(() -> Double.NaN)); // NaN
}
}Here is what happens step by step:
OptionalInt.of(3)makes an OptionalInt that holds 3.OptionalInt.empty()makes one that holds nothing.orElse(0)gives 0 becausenoneis empty.average()on anIntStreamreturns anOptionalDouble, even though the numbers areints, because an average can have a fraction.ifPresentruns the lambda only when a value exists.orElseGetcalls the supplier only when the Optional is empty. Here it returnsNaN, which means "not a number".
What they cannot do
Primitive Optionals have fewer methods than Optional<T>. They have isPresent, isEmpty (Java 11+), orElse, orElseGet, orElseThrow, ifPresent, and ifPresentOrElse. They do not have map, filter, or flatMap.
If you need to transform the value, read it out first with orElse, or use a regular Optional<Integer> instead. For one-off results from a number stream, reading the value directly is usually enough.
Exercise
What does System.out.println(IntStream.of(5, 1, 8).min().orElse(-1)); print, and what type does min() return here?
Show answer
It prints 1. On an IntStream, min() returns an OptionalInt, and orElse(-1) returns its value, 1, because the stream is not empty.
Exercise
You call IntStream.empty().max().getAsInt(). What happens, and how would you rewrite the call to return 0 instead?
Show answer
It throws a NoSuchElementException because the OptionalInt is empty. Write IntStream.empty().max().orElse(0) to get 0 instead.