user3222372
user3222372

Reputation: 382

Transform Map using another Map with the help of Guava

I have a two maps and i want to transform first map value using second map.

Map<T, Double> firstMap = Maps.newHashMap(with some value...);
Map<T, Double> secondMap = Maps.newHashMap(with some value...);

Map<T, Double> finalMap = Maps.newHashMap();
for(Entry<T, Double> entry : firstMap.entrySet())
{
  finalMap.put(entry.getKey(), entry.getValue() * secondMap.get(entry.getKey()));
}

I want to transform first Map in following manner.

The value of element T in first map should be multiplied with its value in second Map. First map is a subset of first map.

Thanks.

Upvotes: 0

Views: 653

Answers (1)

Jeff
Jeff

Reputation: 3882

Using Guava:

public static final void main(final String... args) {

    final Map<String, Integer> map1 = ImmutableMap.of("key0", 2, "key1", 3);

    final Map<String, Integer> map2 = ImmutableMap.of("key0", 2, "key1", 3, "key2", 3);

    final Map<String, Integer> transformed = Maps.transformEntries(map1,
            new EntryTransformer<String, Integer, Integer>() {

                @Override
                public Integer transformEntry(final String key, final Integer value) {

                    return map2.get(key) * value;
                }
            });

    //result {key0=4, key1=9}
    System.out.println(transformed);
}

Upvotes: 1

Related Questions