我有两个如下所示的集合:
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 })
我尝试创建一个 Guava 函数,将列表转换为 Map.Entry 集合:
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));
}
}
但是,此函数需要将此条目列表转换为 map 。
请建议以何种方式可以简化此操作?
最佳答案
如果您使用的是 Java 8,则可以执行以下操作:
Set<String> attributes = Sets.newHashSet("aaa", "bbb", "ccc", "ddd");
Set<String> activeAttributes = Sets.newHashSet("eee", "lll", "ccc", "mmm");
Map<String, Boolean> map = attributes.stream().collect(Collectors.toMap(s -> s, activeAttributes::contains));
System.out.println(map);
对于早期版本的 Java 和 Guava,您可以使用 Maps.asMap
自 Guava 14.0 起:
Map<String, Boolean> map = Maps.asMap(
attributes, Functions.forPredicate(Predicates.in(activeAttributes)));
请注意,这将返回一个实时副本(对集合的任何更改都将反射(reflect)在 map 上)。如果您想要一个不可变的 Map,请使用 Maps.toMap
.
关于java - 将集合转换为 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32738153/