java 取反布尔双函数

java negate boolean BiFunction

我有一个 class,它将检查密钥 is/isn 是否包含在一组密钥中。此条件在 Map 中使用 MathingTypes

进行了描述
public enum MatchingType {
    MATCH, MISMATCH
}

具有匹配类型谓词的映射

Map<MatchingType, Function<Set<String>, Predicate<String>>> predicateMap =
        Map.of(
                MATCH, set -> set::contains,
                MISMATCH, set -> not(set::contains)
        );

用法示例

public boolean isKeyAvailable(String key, MatchingType matchingType, Set<String> keys) {
    return predicateMap.get(matchingType)
                       .apply(keys)
                       .test(key);
}

现在我看到上面的代码可以使用 BiFunction 进行重构。

Map<MatchingType, BiFunction<Set<String>, String, Boolean>> predicateMap =
        Map.of(
                MATCH, Set::contains,
                MISMATCH, Set::contains //how to negate?
        );

public boolean isKeyAvailable(String key, MatchingType matchingType, Set<String> keys) {
    return predicateMap.get(matchingType)
                       .apply(keys, key);
}

可是怎么可能否定Set::contains呢?

截至 there is a static method Predicate.not(Predicate) however, there is not such method in BiPredicate

您可能希望按原样使用 BiPredicate 及其实例方法 negate, which is available since its release as of :

BiPredicate<Set<String>, String> biPredicate = Set::contains;
    
Map<MatchingType, BiPredicate<Set<String>, String>> biPredicateMap =
    Map.of(
        MatchingType.MATCH, biPredicate,
        MatchingType.MISMATCH, biPredicate.negate()
    );
boolean result = biPredicateMap.get(matchingType)
                               .test(keys, key);

基于 Function 的功能接口没有否定,因为它们的 lambda 表达式不能保证 return Boolean.