Skip to content

Instantly share code, notes, and snippets.

@Daomephsta
Created May 17, 2020 05:33
Show Gist options
  • Save Daomephsta/83f915a419b7d76df5c120ad2bacc812 to your computer and use it in GitHub Desktop.
Save Daomephsta/83f915a419b7d76df5c120ad2bacc812 to your computer and use it in GitHub Desktop.
OptionalBoolean
public enum OptionalBoolean
{
TRUE(Boolean.TRUE),
FALSE(Boolean.FALSE),
EMPTY(null);
private final Boolean value;
private OptionalBoolean(Boolean value)
{
this.value = value;
}
public static OptionalBoolean ofNullable(Boolean value)
{
return value == null ? EMPTY : of(value.booleanValue());
}
public static OptionalBoolean of(boolean value)
{
return value ? TRUE : FALSE;
}
public <T> Optional<T> mapTrue(Supplier<T> mapper)
{
Objects.requireNonNull(mapper);
if (this == TRUE)
return Optional.ofNullable(mapper.get());
else
return Optional.empty();
}
public <T> Optional<T> mapFalse(Supplier<T> mapper)
{
Objects.requireNonNull(mapper);
if (this == FALSE)
return Optional.ofNullable(mapper.get());
else
return Optional.empty();
}
public OptionalBoolean ifTrue(Runnable runnable)
{
if (this == TRUE)
runnable.run();
return this;
}
public OptionalBoolean ifFalse(Runnable runnable)
{
if (this == FALSE)
runnable.run();
return this;
}
public OptionalBoolean ifAbsent(Runnable runnable)
{
if (this == EMPTY)
runnable.run();
return this;
}
public boolean orElse(boolean fallback)
{
return this != EMPTY ? value : fallback;
}
public boolean orElseGet(BooleanSupplier fallbackSupplier)
{
return this != EMPTY ? value : fallbackSupplier.getAsBoolean();
}
public <X extends Throwable> boolean orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
{
if (this != EMPTY)
return value;
else
throw exceptionSupplier.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment