使用 google 个集合映射相同的键和值
Map same key and value using google collections
我需要验证映射(字符串到字符串)条目是否不包含相同的键值对(不区分大小写)。例如-
("hello", "helLo") // is not a valid entry
我想知道 Google 集合的 Iterable
与 Predicates
相结合是否可以轻松解决这个问题。
是的,我可以有一个简单的条目迭代器来自己完成,但考虑到任何已经完成的事情。
正在寻找符合 Iterables.tryFind(fromToMaster, Predicates.isEqualEntry(IGNORE_CASE)).isPresent()
的内容
如果你想使用 guava,你可以使用 Maps
实用程序,特别是 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
方法来迭代地图的条目集。为了使条件更具可读性,我会将谓词分配给您正在使用的 class 的变量或成员字段。
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());
}
我需要验证映射(字符串到字符串)条目是否不包含相同的键值对(不区分大小写)。例如-
("hello", "helLo") // is not a valid entry
我想知道 Google 集合的 Iterable
与 Predicates
相结合是否可以轻松解决这个问题。
是的,我可以有一个简单的条目迭代器来自己完成,但考虑到任何已经完成的事情。
正在寻找符合 Iterables.tryFind(fromToMaster, Predicates.isEqualEntry(IGNORE_CASE)).isPresent()
如果你想使用 guava,你可以使用 Maps
实用程序,特别是 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
方法来迭代地图的条目集。为了使条件更具可读性,我会将谓词分配给您正在使用的 class 的变量或成员字段。
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());
}