如何在两个映射中求和值并使用guava返回值

如何将两个映射中的值相加并使用guava返回带有求和值的映射? 可以安全地假设,两个地图将具有相同的密钥集。

例如:

Map filteredPrice [ 1 : 100 ] [ 2 : 50 ] [ 3 : 200 ] 

其他地图

 Map pkgPrice [ 1 : 10 ] [ 2 : 20 ] [ 3 : 30 ] 

总结地图

 Map sumPrice [ 1 : 110 ] [ 2 : 70 ] [ 3 : 230 ] 

我知道我可以遍历这些地图并轻松地对值进行求和,但有一种更简洁的方法可以使用其中一种番石榴方法吗?

番石榴贡献者在这里。

如果您确定两张地图都有相同的按键,我您可以这样做

 Maps.transformEntries(pkgPrice, new EntryTransformer() { public BigDecimal transformEntry(OccupancyType key, BigDecimal pkPrice) { return pkPrice.add(filteredPrice.get(key)); } }); 

但话虽如此,这似乎完全属于“直接方法最干净”的范畴。 (此外,除非您进行复制,否则此实现将在每次请求时重新计算值。但是,这几乎肯定是不必要的复杂;直接的,强制性的方法几乎肯定在这里。

使用functionaljava :

您可以为map定义一个monoid实例。 (我很惊讶这个库中还没有 。)

 public static  Monoid> mapMonoid(final Monoid valueMonoid) { return new Monoid>( // associative binary operation new F2, Map, Map>() { public Map f(Map m1, Map m2) { // logic for merging two maps } }, // identity new HashMap() ); } 

然后使用它:

 Map mergedMap = mapMonoid(Monoid.intAdditionMonoid).sum(m1, m2); 

这样,您甚至可以汇总地图列表。

 List> maps = /* list of maps */; Map total = mapMonoid(Monoid.intAdditionMonoid).sumLeft(maps);