Small package that brings DOP of Optional to Java.
Gives you the possibility to write code as
import io.github.ashr123.option.None;
import io.github.ashr123.option.Option;
import io.github.ashr123.option.Some;
public record Pair<L, R>(L left, R right) {
}
public static Integer intABSOption(Integer integer) {
return switch (Option.of(integer)) {
case Some(Integer i) when i < 0 -> -i;
case Some(Integer i) -> i;
case None<Integer> ignored -> null;
};
}
public static Integer intMax(Pair<Integer, Integer> pair) {
return switch (Option.of(pair)) {
case Some(Pair(Integer l, Integer r)) when l != null && r == null -> l;
case Some(Pair(Integer l, Integer r)) when l == null && r != null -> r;
case Some(Pair(Integer l, Integer r)) when l != null && r != null && l > r -> l;
case Some(Pair(Integer l, Integer r)) -> r;
case None<Pair<Integer, Integer>> ignored -> null;
};
}
Optional methods |
Option<T> opt equivalent |
---|---|
empty() |
None.instance() |
of(T value) |
new Some<>(T value) |
ofNullable(T value) |
|
get() |
|
isPresent() |
if (opt instanceof Some<?>) ... |
isEmpty() |
if (opt instanceof None<?>) ... |
ifPresent(Consumer<? super T> action) |
|
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) |
switch-case |
filter(Predicate<? super T> predicate) |
if (opt instanceof Some(T value) && value ...) |
map(Function<? super T, ? extends U> mapper) |
|
flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) |
flatMap(Function<? super T, ? extends Option<? extends U>> mapper) |
or(Supplier<? extends Optional<? extends T>> supplier) |
switch-case |
stream() |
stream() |
orElse(T other) |
switch-case |
orElseGet(Supplier<? extends T> supplier) |
switch-case |
orElseThrow() |
switch-case |
orElseThrow(Supplier<? extends X> exceptionSupplier) |
switch-case |
Requires JRE 21 or above.