![](/img/trans.png)
[英]How can I use guava FluentIterable to simplify Maps transformations?
[英]how can I sum the values in two maps and return the value using guava
如何在兩個映射中求和並使用番石榴返回具有求和值的映射? 可以安全地假設,兩個地圖將具有相同的鍵集。
例如:
Map<OccupancyType, BigDecimal> filteredPrice
[ 1 : 100 ]
[ 2 : 50 ]
[ 3 : 200 ]
其他地圖
Map<OccupancyType, BigDecimal> pkgPrice
[ 1 : 10 ]
[ 2 : 20 ]
[ 3 : 30 ]
匯總圖
Map<OccupancyType, BigDecimal> sumPrice
[ 1 : 110 ]
[ 2 : 70 ]
[ 3 : 230 ]
我知道我可以遍歷這些映射並輕松地將值求和,但是有沒有一種更干凈的方法使用番石榴方法之一來做到這一點呢?
番石榴的貢獻者在這里。
如果您確定兩個地圖都具有相同的鍵,我想您可以
Maps.transformEntries(pkgPrice,
new EntryTransformer<OccupancyType, BigDecimal, BigDecimal>() {
public BigDecimal transformEntry(OccupancyType key, BigDecimal pkPrice) {
return pkPrice.add(filteredPrice.get(key));
}
});
但是,這似乎完全屬於“直接方法最干凈”的范疇。 (此外,此實現將在您每次請求值時重新計算值,除非您進行復制。但是,這幾乎肯定是不必要的復雜;在此,直接,命令式方法無疑是更可取的。
使用functionaljava :
您可以為map定義一個monoid實例。 (令我驚訝的是庫中還沒有此文件 。)
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>()
);
}
然后使用它:
Map<Integer, Integer> mergedMap =
mapMonoid(Monoid.intAdditionMonoid).sum(m1, m2);
這樣,您甚至可以匯總地圖列表。
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.