如何在两个地图中求值并使用番石榴返回值 [英] how can I sum the values in two maps and return the value using guava

查看:101
本文介绍了如何在两个地图中求值并使用番石榴返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算两个地图中的值,并使用番石榴返回地图的总和值?可以安全地假设两个地图都具有相同的密钥集。

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.

例如:

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

其他地图

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

Summed map

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 ?

推荐答案

这里的番石榴贡献者。

如果你确定两个地图都有相同的键,我想你可以做

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.

这篇关于如何在两个地图中求值并使用番石榴返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆