Last active
August 29, 2015 14:18
-
-
Save bassemZohdy/9f9bfe31f87721fdb5f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Optional; | |
import java.util.function.Consumer; | |
public class OptionalConsumerMain { | |
public static void main(String[] args) { | |
Optional<String> o = Optional.ofNullable(null); | |
OptionalConsumer.of(o) | |
.ifPresent(s -> System.out.println("isPresent " + s)) | |
.ifNotPresent(() -> System.out.println("! isPresent")); | |
} | |
static class OptionalConsumer<T> { | |
private Optional<T> optional; | |
private OptionalConsumer(Optional<T> optional) { | |
this.optional = optional; | |
} | |
public static <T> OptionalConsumer<T> of(Optional<T> optional) { | |
return new OptionalConsumer<>(optional); | |
} | |
public OptionalConsumer<T> ifPresent(Consumer<T> c) { | |
optional.ifPresent(c); | |
return this; | |
} | |
// did not like to use Runnable but I could not find any other alternative | |
public OptionalConsumer<T> ifNotPresent(Runnable r) { | |
if (!optional.isPresent()) | |
r.run(); | |
return this; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment