Sub topic 11
Primitive Optionals
The earlier chapters used Optional<T>, where T is a class such as String or Customer. Java also has three smaller cousins built for plain numbers: OptionalInt, OptionalLong, and OptionalDouble. This chapter explains what they are, why they exist, and how to use them without surprises.
Primitives and Boxing in One Minute
A primitive is one of Java's built-in basic value types, such as int, long, or double. A primitive is not an object. It is just a raw number stored directly in memory.
Generics like Optional<T> only work with objects. You cannot write Optional<int>. You have to write Optional<Integer>, where Integer is a wrapper class: a class whose only job is to hold one primitive value inside an object.
Turning an int into an Integer is called boxing. Turning it back is called unboxing. Java does both for you automatically, which is handy. The cost is that every boxed number is a separate object, and creating many small objects takes extra memory and time.
The primitive optionals avoid that cost. An OptionalInt holds a plain int, with no Integer wrapper involved.
The Three Primitive Optionals
Each type matches one primitive.
| Type | Holds a | Read the value with | Package |
|---|---|---|---|
| `OptionalInt` | `int` | `getAsInt()` | `java.util` |
| `OptionalLong` | `long` | `getAsLong()` | `java.util` |
| `OptionalDouble` | `double` | `getAsDouble()` | `java.util` |
They work the same way as Optional<T>. Each one is a box that is either empty or holds exactly one number. The main difference is the method names: where Optional has get(), these have getAsInt(), getAsLong(), and getAsDouble().
Creating and Reading an OptionalInt
You create primitive optionals with of and empty, just like regular Optionals.
import java.util.OptionalInt;
public class PrimitiveBasics {
public static void main(String[] args) {
OptionalInt score = OptionalInt.of(42);
OptionalInt noScore = OptionalInt.empty();
System.out.println(score.isPresent()); // true
System.out.println(noScore.isEmpty()); // true (Java 11+)
System.out.println(score.getAsInt()); // 42
System.out.println(noScore.orElse(0)); // 0
System.out.println(noScore.orElseGet(() -> 7)); // 7
}
}Here is what each line does:
OptionalInt.of(42)makes a box holding the number 42.OptionalInt.empty()makes an empty box.isPresent()andisEmpty()tell you whether a number is inside.getAsInt()returns the number. It throws an error if the box is empty.orElse(0)returns the number, or 0 if the box is empty.orElseGet(() -> 7)runs the lambda only when the box is empty. The lambda is anIntSupplier, which is a function that takes nothing and returns anint.
Where Primitive Optionals Come From
You will rarely create these types by hand. Most of the time a primitive stream gives them to you. A primitive stream is a stream of raw numbers: IntStream, LongStream, or DoubleStream. Some of their operations may have no answer. For example, the largest number in an empty list does not exist. Those operations return a primitive optional.
Notice that average() always returns an OptionalDouble, even on an IntStream. That is because the average of whole numbers is often a fraction.
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class ThreeKinds {
public static void main(String[] args) {
OptionalInt highest = IntStream.of(70, 85, 92).max();
OptionalLong smallest = LongStream.of(5_000_000_000L, 3L).min();
OptionalDouble mean = IntStream.of(70, 85, 92).average();
System.out.println(highest.getAsInt()); // 92
System.out.println(smallest.getAsLong()); // 3
System.out.println(mean.getAsDouble()); // 82.33333333333333
}
}In this example we know the streams have numbers in them, so calling getAsInt() directly is safe. With real data you usually don't know that, so prefer orElse or orElseThrow.
Edge Cases with Empty Streams
Not every stream operation returns an optional. This can surprise beginners.
import java.util.OptionalDouble;
import java.util.stream.IntStream;
public class EmptyCases {
public static void main(String[] args) {
OptionalDouble avg = IntStream.empty().average();
System.out.println(avg.isPresent()); // false
int total = IntStream.empty().sum();
System.out.println(total); // 0
long count = IntStream.empty().count();
System.out.println(count); // 0
}
}The rule is simple. If the operation has a sensible answer for "no numbers", it returns a plain number. The sum of nothing is 0 and the count of nothing is 0. If there is no sensible answer, it returns an optional. Nothing has no average, no maximum, and no minimum.
| Operation on an empty `IntStream` | Return type | Result |
|---|---|---|
| `sum()` | `int` | `0` |
| `count()` | `long` | `0` |
| `max()` / `min()` | `OptionalInt` | empty |
| `average()` | `OptionalDouble` | empty |
| `findFirst()` | `OptionalInt` | empty |
Acting on the Value
Primitive optionals support the same action methods you learned for Optional, with primitive-friendly function types.
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class ActOnValue {
public static void main(String[] args) {
OptionalInt firstEven = IntStream.of(3, 8, 5).filter(n -> n % 2 == 0).findFirst();
firstEven.ifPresent(n -> System.out.println("First even: " + n));
IntStream.of(1, 3).filter(n -> n % 2 == 0).findFirst().ifPresentOrElse(
n -> System.out.println("First even: " + n),
() -> System.out.println("No even numbers"));
int value = firstEven.orElseThrow(
() -> new IllegalStateException("Expected an even number"));
System.out.println(value); // 8
}
}The program prints:
First even: 8
No even numbers
8ifPresenttakes anIntConsumer, which is a function that receives anintand returns nothing.ifPresentOrElse(Java 9+) also takes aRunnablefor the empty case.orElseThrowthrows your exception when the box is empty. Java 10 added a version with no arguments that throwsNoSuchElementException.
What Primitive Optionals Cannot Do
Primitive optionals have fewer methods than Optional<T>. They have no map, filter, flatMap, or or. You cannot write a chain like optInt.map(n -> n * 2).
| Method | `Optional<T>` | `OptionalInt` / `Long` / `Double` |
|---|---|---|
| `of`, `empty` | Yes | Yes |
| `ofNullable` | Yes | No |
| `isPresent`, `isEmpty` | Yes | Yes |
| `get` / `getAsInt` etc. | Yes | Yes |
| `orElse`, `orElseGet`, `orElseThrow` | Yes | Yes |
| `ifPresent`, `ifPresentOrElse` | Yes | Yes |
| `stream` | Yes | Yes (returns a primitive stream) |
| `map`, `filter`, `flatMap`, `or` | Yes | No |
When you need those methods, you have two choices.
The first is to work with the plain number after you take it out:
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class NoMapWorkaround {
public static void main(String[] args) {
OptionalInt max = IntStream.of(4, 10, 6).max();
int doubled = max.isPresent() ? max.getAsInt() * 2 : 0;
System.out.println(doubled); // 20
}
}The second is to convert to a regular Optional<Integer>, which brings back boxing but gives you the full set of methods:
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class ConvertToOptional {
public static void main(String[] args) {
OptionalInt max = IntStream.of(4, 10, 6).max();
Optional<Integer> boxed = max.stream().boxed().findFirst(); // Java 9+
String label = boxed
.filter(n -> n > 5)
.map(n -> "Big max: " + n)
.orElse("Small or missing");
System.out.println(label); // Big max: 10
}
}max.stream() gives an IntStream with zero or one number. boxed() turns it into a Stream<Integer>. Then findFirst() returns an Optional<Integer>.
Choosing Between OptionalInt and Optional<Integer>
Use this as a quick guide:
- A primitive stream gave you an
OptionalInt: keep it and read it withorElseororElseThrow. This is the most common case. - You return a "maybe number" from your own method:
OptionalIntis fine and shows clearly that the value is anint. ChooseOptional<Integer>if callers will wantmaporfilter. - You need to put it in a generic structure such as
List<Optional<Integer>>: useOptional<Integer>.OptionalIntis not generic and does not fit there.
A Common Mistake
The most frequent error is calling getAsInt() without checking first.
import java.util.NoSuchElementException;
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class CommonMistake {
public static void main(String[] args) {
OptionalInt max = IntStream.empty().max();
try {
System.out.println(max.getAsInt());
} catch (NoSuchElementException e) {
System.out.println("Caught: " + e.getMessage()); // Caught: No value present
}
System.out.println(max.orElse(-1)); // -1
}
}getAsInt() on an empty box throws NoSuchElementException, just like get() on Optional. Prefer orElse, orElseGet, or orElseThrow with a clear message.
Exercise
What type does IntStream.of(2, 4, 7).average() return, and what does calling getAsDouble() on it print?
Show answer
It returns an OptionalDouble, because an average can be a fraction and an empty stream has no average. getAsDouble() prints 4.333333333333333 (13 divided by 3).
Exercise
Why does IntStream.empty().sum() return 0 as a plain int, while IntStream.empty().max() returns an empty OptionalInt?
Show answer
The sum of no numbers has a sensible answer, 0, so no optional is needed. The maximum of no numbers does not exist, so the result must be able to say "no value", which is what an empty OptionalInt does.
Exercise
You have OptionalInt length = IntStream.of(3, 12, 8).max(); Write one expression that gives "long" if the value is greater than 10, "short" if it is 10 or less, and "none" if the OptionalInt is empty. OptionalInt has no filter or map, so use a different approach.
Show answer
One answer is: length.isEmpty() ? "none" : (length.getAsInt() > 10 ? "long" : "short"). This gives "long" here. Another is to convert first: length.stream().boxed().findFirst().map(n -> n > 10 ? "long" : "short").orElse("none"). Note that isEmpty needs Java 11 and stream needs Java 9.