如果你想使用guava,你可以使用Maps utils,特别是filterEntries 函数。
仅过滤键不等于值的条目(忽略大小写)的示例可能如下所示
Map<String, String> map = new HashMap<>();
map.put("hello", "helLo");
map.put("Foo", "bar");
Map<String, String> filtered = Maps.filterEntries(map, new Predicate<Map.Entry<String, String>>() {
@Override
public boolean apply(Map.Entry<String, String> input) {
return !input.getKey().equalsIgnoreCase(input.getValue());
}
});
System.out.println(filtered); // will print {Foo=bar}
但是 guava 的 Predicates 中没有默认谓词,我知道它可以满足您的需求。
加法:
如果您想要一个验证机制而不创建新映射,您可以使用Iterables 和any 方法迭代映射的条目集。为了使条件更具可读性,我会将谓词分配给您正在使用的类的变量或成员字段。
Predicate<Map.Entry<String, String>> keyEqualsValueIgnoreCase = new Predicate<Map.Entry<String, String>>() {
@Override
public boolean apply(Map.Entry<String, String> input) {
return input.getKey().equalsIgnoreCase(input.getValue());
}
};
if (Iterables.any(map.entrySet(), keyEqualsValueIgnoreCase)) {
throw new IllegalStateException();
}
或者如果需要入口,可以使用Iterables#tryFind方法,使用返回的Optional
Optional<Map.Entry<String, String>> invalid = Iterables.tryFind(map.entrySet(), keyEqualsValueIgnoreCase);
if(invalid.isPresent()) {
throw new IllegalStateException("Invalid entry " + invalid.get());
}