【发布时间】:2015-12-28 22:33:59
【问题描述】:
我想用加权平均值进行一些计算。有两张地图
Map<String, Double> weightedVector;
Map<String, Double> otherVector;
伪算法是这样的
foreach entry in weightedVector:
get same entry from otherVector
- if it exists then multiply weights and add new entry to another map
- otherwise do nothing
我想利用 Stream API 并想出了这个
Stream<Double> map = weightedVector.entrySet().parallelStream()
.map(entry -> {
Double t = otherVector.get(entry.getKey());
Double v = entry.getValue();
return (t != null && v != null)
? t * v
: 0.0;
});
我问自己一个问题,使用旧样式访问otherVector 是否是一种好习惯,就像上面的 sn-p 一样。
对我来说主要问题是我有两个输入映射,并且想要获得相同类型的输出映射,但上面的代码从计算中得到了 Stream 和 Double。
我最好使用stream().collect(..),然后如何?
最好不要使用HashMap,而是创建一个包含键值对的容器对象并改用它?
【问题讨论】:
-
那么,当在另一个地图中没有找到任何条目时(如您的描述所述),您想什么都不做,还是要存储 0.0(如您的代码所示)?
标签: java java-8 java-stream collect