CKTIS / Java
util.OptionalInt: practical reference
util.OptionalInt: practical reference: OptionalInt represents one present primitive int or absence and avoids creating an Integer object.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.util.OptionalIntOptionalInt represents one present primitive int or absence and avoids creating an Integer object.
Use it for an optional integral result when zero and negative numbers are valid data rather than absence sentinels.
Do not synchronize on this value-based instance or assume its identity; getAsInt throws NoSuchElementException when empty.
of(0) is present and empty is a separate state; stream has one element or none, and orElseThrow creates an exception only when absent.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var value = java.util.OptionalInt.of(7);
System.out.println(value.getAsInt());
}
}
Result
7
The example exercises the documented element in a small deterministic program and compares exact standard output.