【问题标题】:Map same key and value using google collections使用谷歌集合映射相同的键和值
【发布时间】:2015-04-16 09:41:02
【问题描述】:

我需要验证映射(字符串到字符串)条目是否不包含相同的键和值对(不区分大小写)。比如——

("hello", "helLo") // is not a valid entry

我想知道 Google 集合的 IterablePredicates 结合是否可以轻松解决这个问题。

是的,我可以有一个简单的条目迭代器来自己做,但考虑到任何事情都已经完成了。

寻找与Iterables.tryFind(fromToMaster, Predicates.isEqualEntry(IGNORE_CASE)).isPresent() 一致的东西

【问题讨论】:

  • 地图是否包含任何无效条目是否需要布尔值?还是您想要过滤后的地图?
  • 在这种情况下我会抛出异常。

标签: java apache dictionary guava


【解决方案1】:

如果你想使用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 中没有默认谓词,我知道它可以满足您的需求。

加法:

如果您想要一个验证机制而不创建新映射,您可以使用Iterablesany 方法迭代映射的条目集。为了使条件更具可读性,我会将谓词分配给您正在使用的类的变量或成员字段。

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());
}

【讨论】:

  • 它不会创建新地图吗?我的意思是地图构建的额外开销?
  • 我认为简单的条目迭代可能比这种实现更有效,除非我遗漏了什么?
  • 是的。我添加了一种替代方法,可以避免创建地图并引发异常。
  • 看起来很棒。谢谢。
  • 我知道我要求额外的,但我们能否获得导致 IllegalStateException 的条目作为回报(可能是字符串)?我想显示它,以便用户可以在失败的地方获得额外的信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多