Created
April 25, 2014 20:34
-
-
Save mikaelhg/11302376 to your computer and use it in GitHub Desktop.
Lambda / Optional demos
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
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