问题描述
我有一个类,它将检查一组密钥中是否包含一个密钥。 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
?
解决方法
从java-11开始,有一个静态方法Predicate.not(Predicate)
,但是在BiPredicate
中没有这样的方法。
您可能希望像实例方法negate
一样使用BiPredicate
,该实例方法自java-8发行以来就可用:
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
。