Java : Optional with Examples
Optional (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Optional methods.
Summary
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 ()
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)
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)
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)
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 ()
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 ()
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)
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)
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 ()
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 ()
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)
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)
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)
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)
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)
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)
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 ()
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)
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 ()
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 ()
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