Skip to content

Instantly share code, notes, and snippets.

@iamminster
Last active January 31, 2020 05:59
Show Gist options
  • Save iamminster/a0ebe04009aa89862701f30b2f765327 to your computer and use it in GitHub Desktop.
Save iamminster/a0ebe04009aa89862701f30b2f765327 to your computer and use it in GitHub Desktop.
/*
This is an useful utility class to convert Method References to Functional References
Example:
// Processing Java Stream: Couting empty strings using Method references
Stream.of("A", "", "B").filter(String::isEmpty).count() --> result: 1
// But it is impossible to count non-empty string using the same method
There is no !String::isEmpty or String::isNotEmpty
// However using Java type references mechanism we can in-directly translate Method references to Functional references
// but, String::isEmpty can be translated to 1.Predicate<String> or 2.Function<String, Boolean>
// so we need to explicitly specify which Functional references it should be translated to.
// Using this below class, we can count non-empty string as:
Stream.of("A", "", "B").filter(Predicates.negate(String::isEmpty)).count() --> result: 2
*/
public final Predicates {
private Predicates {}
// convert Method reference to Functional reference
public static <T> Predicate<T> of(final Predicate<T> predicate) {
Objects.requireNonNull(predicate, "Predicate must be specified");
return predicate;
}
public static <T> Predicate<T> negate(final Predicate<T> predicate) {
Objects.requireNonNull(predicate, "Predicate must be specified");
return predicate.negate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment