Skip to content

Instantly share code, notes, and snippets.

@mikaelhg
Created April 25, 2014 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelhg/11302376 to your computer and use it in GitHub Desktop.
Save mikaelhg/11302376 to your computer and use it in GitHub Desktop.
Lambda / Optional demos
private static <T> boolean fillIf(final Supplier<T> supplier, final Consumer<T> consumer) {
return fillIf(supplier, consumer, null);
}
private static <T> boolean fillIf(final Supplier<? extends T> supplier, final Consumer<T> consumer, final Consumer<Exception> exceptionHandler) {
try {
final T data = supplier.get();
if (null == data) {
return false;
}
consumer.accept(data);
return true;
} catch (final Exception e) {
if (exceptionHandler != null) {
exceptionHandler.accept(e);
}
return false;
}
}
private static Optional<Matcher> ifFound(final Pattern pattern, final String text, final Consumer<Matcher> consumer) {
final Matcher m = pattern.matcher(text);
if (m.find()) {
consumer.accept(m);
return Optional.of(m);
}
return Optional.empty();
}
private static <T> Optional<T> transform(final Pattern pattern, final String text, final Function<Matcher, T> transformer) {
final Matcher m = pattern.matcher(text);
if (m.find()) {
return Optional.of(transformer.apply(m));
} else {
return Optional.empty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment