将集合转换为地图

时间:2015-09-23 11:18:37

标签: java java-7 guava

我有两个如下集合:

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

但是,此函数需要将此条目列表转换为映射。

请建议以哪种方式简化?

1 个答案:

答案 0 :(得分:4)

如果您使用的是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)));

请注意,这会返回实时副本(对该集的任何更改都将反映在地图上)。如果您想要一个不可变的Map,请使用Maps.toMap