Java否定布尔BiFunction

问题描述

我有一个类,它将检查一组密钥中是否包含一个密钥。 Map中使用MathingType s

描述了这些条件
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,Set::contains //how to negate?
        );

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

但是如何排除Set::contains

解决方法

开始,有一个静态方法Predicate.not(Predicate),但是在BiPredicate中没有这样的方法。

您可能希望像实例方法negate一样使用BiPredicate,该实例方法自发行以来就可用:

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表达式返回Boolean

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...