【发布时间】:2015-09-23 11:18:36
【问题描述】:
我有两个收藏,如下所示:
Set<String> attributes = Sets.newHashSet("aaa", "bbb", "ccc", "ddd");
Set<String> activeAttributes = Sets.newHashSet("eee", "lll", "ccc", "mmm");
将这些集合转换为映射的想法,假设 attributes 集合应用作此映射的键,并且在计算值期间应使用 activeAttributes(如果 activeAttributes 包含来自集合 attributes 的值则为“true”,否则应设置“false”参数):
例如:
({aaa -> false, bbb -> false, ccc -> true, ddd -> false })
我尝试创建一个将列表转换为 Map.Entry 集合的 Guava 函数:
private static class ActiveAttributesFunction implements Function<String, Map.Entry<String, Boolean>> {
private Set<String> activeAttributes;
public ActiveAttributesFunction (Set<String> activeAttributes) {
this.activeAttributes = activeAttributes;
}
@Override
public Map.Entry<String, Boolean> apply(String input) {
return Maps.immutableEntry(input, activeAttributes.contains(input));
}
}
但是,此函数需要将此条目列表转换为映射。
请建议可以通过哪种方式简化?
【问题讨论】:
-
你不想使用标准的“for”循环?