OptionalUtils { public static <T> Optional<T> executeIfEmpty(Optional<T> optional, Operation operation) { if (!optional.isPresent()) { operation.perform(); } return optional; }  static Optional<T> executeIfEmpty(Optional<T> optional, Operation operation); static boolean containsDifferent(Optional<T> requestValue, T storeValue); static boolean matches(Optional<T> optional1, Optional<U> optional2, BiPredicate<T, U> biPredicate);  }
@Test void ifEmptyShouldPreserveValueOfEmptyOptionals() { Optional<Object> expected = OptionalUtils.executeIfEmpty(Optional.empty(), () -> { }); assertThat(expected).isEmpty(); }
@Test void ifEmptyShouldPreserveValueOfPresentOptionals() { String value = "value"; Optional<String> expected = OptionalUtils.executeIfEmpty(Optional.of(value), () -> { }); assertThat(expected).contains(value); }
@Test void ifEmptyShouldPerformOperationIfEmpty() { AtomicInteger operationCounter = new AtomicInteger(0); OptionalUtils.executeIfEmpty(Optional.empty(), operationCounter::incrementAndGet); assertThat(operationCounter.get()).isEqualTo(1); }
@Test void ifEmptyShouldNotPerformOperationIfPresent() { AtomicInteger operationCounter = new AtomicInteger(0); OptionalUtils.executeIfEmpty(Optional.of("value"), operationCounter::incrementAndGet); assertThat(operationCounter.get()).isEqualTo(0); }