Sometimes I want to use the Optional’s feature with if/else plausibility check and discover that an outside variable would come in handy.
There are different ways of doing it but here is mine:
AtomicReference<Optional<Foo>> outsideVar = new AtomicReference<>(Optional.empty());
optional.ifPresentOrElse(filledOptional -> {
LOGGER.info("Something happened: {}", filledOptional);
outsideVar.set(Optional.of(new Foo(filledOptional)));
}, () -> {
LOGGER.error("Empty value!");
}
);