fashuser
fashuser

Reputation: 1489

Convert Collection to Map

I have two collections like below:

Set<String> attributes = Sets.newHashSet("aaa", "bbb", "ccc", "ddd");
Set<String> activeAttributes = Sets.newHashSet("eee", "lll", "ccc", "mmm");

The idea to convert these collections to a map, given that attributes collection should be used as keys of this map and activeAttributes should be used during calculating value (In case activeAttributes contains value from collection attributes then "true", otherwise "false" parameter should be set):

As example:

({aaa -> false, bbb -> false, ccc -> true, ddd -> false })

I've tried to create a Guava function that converts list to collection of 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));
    }
}

But, this function will require to convert this list of entries to map.

Please suggest in which way this can be simplified?

Upvotes: 2

Views: 9458

Answers (1)

Tunaki
Tunaki

Reputation: 137319

If you are using Java 8, you can do the following:

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

For an earlier version of Java and with Guava, you can use Maps.asMap since Guava 14.0:

Map<String, Boolean> map = Maps.asMap(
    attributes, Functions.forPredicate(Predicates.in(activeAttributes)));

Note that this returns a live copy (any changes to the set will be reflected on the map). If you want an immutable Map, use Maps.toMap.

Upvotes: 4

Related Questions