Java : Optional with Examples
Optional (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Optional methods.
Summary
A container object which may or may not contain a non-null value. If a value is present, isPresent() returns true. If no value is present, the object is considered empty and isPresent() returns false.
API examples on this page uses the Sample class below.
public class Sample<T> {
private final T value;
public Sample(T value) {
this.value = value;
}
public Optional<T> getValue() {
return Optional.ofNullable(value);
}
}
final var sample = new Sample<>("abcd");
sample.getValue().ifPresent(value -> {
System.out.println("value : " + value);
});
// Result
// ↓
//value : abcd
final var sample = new Sample<>(null);
sample.getValue().ifPresentOrElse(value -> {
System.out.println("value : " + value);
}, () -> {
System.out.println("value : null!");
});
// Result
// ↓
//value : null!
Methods
static <T> Optional<T> empty ()
Returns an empty Optional instance.
final var opt = Optional.empty();
System.out.println(opt); // Optional.empty
System.out.println(opt.isEmpty()); // true
//opt.orElseThrow(); // NoSuchElementException: No value present
boolean equals (Object obj)
Indicates whether some other object is "equal to" this Optional.
final var opt1 = Optional.of(100);
final var opt2 = Optional.of(100);
final var opt3 = Optional.of(999);
System.out.println(opt1.equals(opt2)); // true
System.out.println(opt1.equals(opt3)); // false
final var opt1 = Optional.of("abcd");
final var opt2 = Optional.of("XYZ");
System.out.println(opt1.equals(opt2)); // false
final var opt1 = Optional.empty();
final var opt2 = Optional.empty();
System.out.println(opt1.equals(opt2)); // true
Optional<T> filter (Predicate<? super T> predicate)
If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.
final var sample = new Sample<>("abcd");
final var ret1 = sample.getValue().filter(s -> {
System.out.println("filter : " + s);
return s.equals("abcd");
});
System.out.println("ret : " + ret1);
// Result
// ↓
//filter : abcd
//ret : Optional[abcd]
final var ret2 = sample.getValue().filter(s -> {
System.out.println("filter : " + s);
return s.equals("XYZ");
});
System.out.println("ret : " + ret2);
// Result
// ↓
//filter : abcd
//ret : Optional.empty
final var sample = new Sample<>(null);
final var ret = sample.getValue().filter(s -> {
System.out.println("filter : " + s);
return s.equals("abcd");
});
System.out.println("ret : " + ret);
// Result
// ↓
//ret : Optional.empty
<U> Optional<U> flatMap (Function<? super T,? extends Optional<? extends U>> mapper)
If a value is present, returns the result of applying the given Optional-bearing mapping function to the value, otherwise returns an empty Optional.
final var sample = new Sample<>("abcd");
final var ret = sample.getValue().flatMap(s -> {
System.out.println("flatMap : " + s);
return Optional.of(s.toUpperCase());
});
System.out.println("ret : " + ret);
// Result
// ↓
//flatMap : abcd
//ret : Optional[ABCD]
final var sample = new Sample<>(255);
final var ret1 = sample.getValue().flatMap(i -> {
System.out.println("flatMap : " + i);
return Optional.of(i * 2);
});
System.out.println("ret : " + ret1);
// Result
// ↓
//flatMap : 255
//ret : Optional[510]
final var ret2 = sample.getValue().flatMap(i -> {
System.out.println("flatMap : " + i);
return Optional.of("0x" + Integer.toHexString(i));
});
System.out.println("ret : " + ret2);
// Result
// ↓
//flatMap : 255
//ret : Optional[0xff]
final var sample = new Sample<>(null);
final var ret = sample.getValue().flatMap(s -> {
System.out.println("flatMap : " + s);
return Optional.empty();
});
System.out.println("ret : " + ret);
// Result
// ↓
//ret : Optional.empty
T get ()
If a value is present, returns the value, otherwise throws NoSuchElementException.
The preferred alternative to this method is orElseThrow().
final var sample = new Sample<>("abcd");
final var opt = sample.getValue();
if (opt.isPresent()) {
System.out.println(opt.get()); // abcd
}
final var sample = new Sample<>(null);
//sample.getValue().get(); // NoSuchElementException: No value present
int hashCode ()
Returns the hash code of the value, if present, otherwise 0 (zero) if no value is present.
System.out.println(Optional.empty().hashCode()); // 0
System.out.println(Optional.of(123).hashCode()); // 123
System.out.println("abcd".hashCode()); // 2987074
System.out.println(Optional.of("abcd").hashCode()); // 2987074
void ifPresent (Consumer<? super T> action)
If a value is present, performs the given action with the value, otherwise does nothing.
final var sample = new Sample<>("abcd");
sample.getValue().ifPresent(value -> {
System.out.println("action : " + value);
});
// Result
// ↓
//action : abcd
final var sample = new Sample<>(null);
sample.getValue().ifPresent(value -> {
System.out.println("action : " + value);
});
// Result
// ↓
//<No output>
void ifPresentOrElse (Consumer<? super T> action, Runnable emptyAction)
If a value is present, performs the given action with the value, otherwise performs the given empty-based action.
final var sample = new Sample<>("abcd");
sample.getValue().ifPresentOrElse(value -> {
System.out.println("action : " + value);
}, () -> {
System.out.println("emptyAction!");
});
// Result
// ↓
//action : abcd
final var sample = new Sample<>(null);
sample.getValue().ifPresentOrElse(value -> {
System.out.println("action : " + value);
}, () -> {
System.out.println("emptyAction!");
});
// Result
// ↓
//emptyAction!
boolean isEmpty ()
If a value is not present, returns true, otherwise false.
final var sample = new Sample<>("abcd");
if (sample.getValue().isEmpty()) {
System.out.println("empty!");
} else {
System.out.println("present!");
}
// Result
// ↓
//present!
final var sample = new Sample<>(null);
if (sample.getValue().isEmpty()) {
System.out.println("empty!");
} else {
System.out.println("present!");
}
// Result
// ↓
//empty!
boolean isPresent ()
If a value is present, returns true, otherwise false.
final var sample = new Sample<>("abcd");
if (sample.getValue().isPresent()) {
System.out.println("present!");
} else {
System.out.println("empty!");
}
// Result
// ↓
//present!
final var sample = new Sample<>(null);
if (sample.getValue().isPresent()) {
System.out.println("present!");
} else {
System.out.println("empty!");
}
// Result
// ↓
//empty!
<U> Optional<U> map (Function<? super T,? extends U> mapper)
If a value is present, returns an Optional describing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional.
final var sample = new Sample<>("abcd");
final var ret = sample.getValue().map(s -> {
System.out.println("map : " + s);
return s.toUpperCase();
});
System.out.println("ret : " + ret);
// Result
// ↓
//map : abcd
//ret : Optional[ABCD]
final var ret2 = sample.getValue().map(s -> {
System.out.println("map : " + s);
return null;
});
System.out.println("ret : " + ret2);
// Result
// ↓
//map : abcd
//ret : Optional.empty
final var sample = new Sample<>(255);
final var ret1 = sample.getValue().map(i -> {
System.out.println("map : " + i);
return i * 2;
});
System.out.println("ret : " + ret1);
// Result
// ↓
//map : 255
//ret : Optional[510]
final var ret2 = sample.getValue().map(i -> {
System.out.println("map : " + i);
return "0x" + Integer.toHexString(i);
});
System.out.println("ret : " + ret2);
// Result
// ↓
//map : 255
//ret : Optional[0xff]
final var sample = new Sample<String>(null);
final var ret = sample.getValue().map(s -> {
System.out.println("map : " + s);
return s.toUpperCase();
});
System.out.println("ret : " + ret);
// Result
// ↓
//ret : Optional.empty
static <T> Optional<T> of (T value)
Returns an Optional describing the given non-null value.
final var opt1 = Optional.of(123);
System.out.println(opt1); // Optional[123]
final var opt2 = Optional.of("abc");
System.out.println(opt2); // Optional[abc]
//Optional.of(null); // NullPointerException
static <T> Optional<T> ofNullable (T value)
Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional.
final var opt1 = Optional.ofNullable(123);
System.out.println(opt1); // Optional[123]
final var opt2 = Optional.ofNullable("abc");
System.out.println(opt2); // Optional[abc]
final var opt3 = Optional.ofNullable(null);
System.out.println(opt3); // Optional.empty
Optional<T> or (Supplier<? extends Optional<? extends T>> supplier)
If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
final var sample = new Sample<>("abcd");
final var ret = sample.getValue().or(() -> {
System.out.println("or action!");
return Optional.of("XYZ");
});
System.out.println("ret : " + ret);
// Result
// ↓
//ret : Optional[abcd]
final var sample = new Sample<>(null);
final var ret = sample.getValue().or(() -> {
System.out.println("or action!");
return Optional.of("XYZ");
});
System.out.println("ret : " + ret);
// Result
// ↓
//or action!
//ret : Optional[XYZ]
T orElse (T other)
If a value is present, returns the value, otherwise returns other.
final var sample = new Sample<>("abcd");
final var ret = sample.getValue().orElse("XYZ");
System.out.println(ret); // abcd
final var sample = new Sample<>(null);
final var ret = sample.getValue().orElse("XYZ");
System.out.println(ret); // XYZ
T orElseGet (Supplier<? extends T> supplier)
If a value is present, returns the value, otherwise returns the result produced by the supplying function.
final var sample = new Sample<>("abcd");
final var ret = sample.getValue().orElseGet(() -> {
System.out.println("or action!");
return "XYZ";
});
System.out.println("ret : " + ret);
// Result
// ↓
//ret : abcd
final var sample = new Sample<>(null);
final var ret = sample.getValue().orElseGet(() -> {
System.out.println("or action!");
return "XYZ";
});
System.out.println("ret : " + ret);
// Result
// ↓
//or action!
//ret : XYZ
T orElseThrow ()
If a value is present, returns the value, otherwise throws NoSuchElementException.
final var sample = new Sample<>("abcd");
final var opt = sample.getValue();
if (opt.isPresent()) {
System.out.println(opt.orElseThrow()); // abcd
}
final var sample = new Sample<>(null);
//sample.getValue().orElseThrow(); // NoSuchElementException: No value present
<X extends Throwable> T orElseThrow (Supplier<? extends X> exceptionSupplier)
If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.
final var sample = new Sample<>("abcd");
final var opt = sample.getValue();
if (opt.isPresent()) {
System.out.println(opt.orElseThrow(IllegalStateException::new)); // abcd
}
final var sample = new Sample<>(null);
try {
sample.getValue().orElseThrow(() -> {
throw new IllegalStateException("optional is empty");
});
} catch (IllegalStateException e) {
System.out.println(e);
}
// Result
// ↓
//java.lang.IllegalStateException: optional is empty
Stream<T> stream ()
If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.
final var sample = new Sample<>("abcd");
final var ret1 = sample.getValue().stream().toList();
System.out.println(ret1); // [abcd]
final var ret2 = sample.getValue().stream().count();
System.out.println(ret2); // 1
final var sample = new Sample<>(null);
final var ret1 = sample.getValue().stream().toList();
System.out.println(ret1); // []
final var ret2 = sample.getValue().stream().count();
System.out.println(ret2); // 0
String toString ()
Returns a non-empty string representation of this Optional suitable for debugging.
final var ret1 = Optional.empty().toString();
System.out.println(ret1); // Optional.empty
final var ret2 = Optional.of(123).toString();
System.out.println(ret2); // Optional[123]
final var ret3 = Optional.of("abc").toString();
System.out.println(ret3); // Optional[abc]
Related posts
- API Examples