Skip to content

Instantly share code, notes, and snippets.

@ulrich
Last active April 6, 2021 12:50
Show Gist options
  • Save ulrich/875ce01c50161dddfaa76d76feb89c1b to your computer and use it in GitHub Desktop.
Save ulrich/875ce01c50161dddfaa76d76feb89c1b to your computer and use it in GitHub Desktop.
Pattern matching in Java 8+
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import static java.util.Optional.empty;
import static java.util.Optional.of;
public class PatternMatchingExample {
public static void main(String[] args) {
PatternMatching<? super String, ?> pm =
PatternMatching
.when("world"::equals, x -> "Hello " + x)
.orWhen("monde"::equals, x -> "Salut " + x);
pm.matches("monde").ifPresent(System.out::println);
}
@FunctionalInterface
interface PatternMatching<T, R> {
static <T, R> PatternMatching<T, R> when(Predicate<T> predicate, Function<T, R> action) {
return value -> predicate.test(value) ? of(action.apply(value)) : empty();
}
default PatternMatching<T, R> orWhen(final Predicate<T> predicate, final Function<T, R> action) {
return value -> {
final Optional<R> result = matches(value);
if (result.isPresent()) {
return result;
}
return (predicate.test(value)) ?
of(action.apply(value)) : empty();
};
}
Optional<R> matches(T value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment