简体   繁体   English

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

[英]how can I sum the values in two maps and return the value using guava

How can I sum the values in two maps and return the map with summed values using guava ? 如何在两个映射中求和并使用番石榴返回具有求和值的映射? It can be safely assumed, both maps will have the same set of keys. 可以安全地假设,两个地图将具有相同的键集。

For eg: 例如:

Map<OccupancyType, BigDecimal> filteredPrice
[ 1 : 100 ]
[ 2 : 50 ]
[ 3 : 200 ]

Other map 其他地图

Map<OccupancyType, BigDecimal> pkgPrice
[ 1 : 10 ]
[ 2 : 20 ]
[ 3 : 30 ]

Summed map 汇总图

Map<OccupancyType, BigDecimal> sumPrice
[ 1 : 110 ]
[ 2 : 70 ]
[ 3 : 230 ]

I know I can iterate through these maps and sum the values easily, but is there a cleaner way to do this using one of the guava methods ? 我知道我可以遍历这些映射并轻松地将值求和,但是有没有一种更干净的方法使用番石榴方法之一来做到这一点呢?

Guava contributor here. 番石榴的贡献者在这里。

If you're sure that both maps have the same keys, I suppose you could do 如果您确定两个地图都具有相同的键,我您可以

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

but that said, this seems to fall squarely into the category of "the direct approach is the cleanest." 但是,这似乎完全属于“直接方法最干净”的范畴 (Additionally, this implementation will recompute the values every time you request them, unless you do a copy. Still, this is almost certainly unnecessarily complicated; the direct, imperative approach is almost certainly preferable here. (此外,此实现将在您每次请求值时重新计算值,除非您进行复制。但是,这几乎肯定是不必要的复杂;在此,直接,命令式方法无疑是更可取的。

With functionaljava : 使用functionaljava

You could define a monoid instance for map. 您可以为map定义一个monoid实例。 (I am surprised this is not already present in the library .) (令我惊讶的是库中还没有此文件 。)

public static <K, V> Monoid<Map<K, V>> mapMonoid(final Monoid<V> valueMonoid) {
  return new Monoid<Map<K, V>>(

    // associative binary operation
    new F2<Map<K, V>, Map<K, V>, Map<K, V>>() {
      public Map<K, V> f(Map<K, V> m1, Map<K, V> m2) {
        // logic for merging two maps
      }
    },

    // identity
    new HashMap<K, V>()
  ); 
}

And then use it so: 然后使用它:

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

This way, you can even sum a list of maps. 这样,您甚至可以汇总地图列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM