Java Stream Api - 操作Map<String, Double>的好方法?
Java Stream Api - good ways to operate on Map<String, Double>?
我想用加权平均值做一些计算。有两张地图
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
是否是一种好习惯。
我的主要问题是我有两个输入映射并且想要获得相同类型的输出映射但是上面的代码从计算中得到了 Stream
的 Double
。
我使用 stream().collect(..)
更好吗?
不使用 HashMap
而是创建一个包含键值对的容器对象并使用它可能更好吗?
假设在没有对应条目的情况下你真的什么都不做:
Map<String, Double> result =
weightedVector.entrySet()
.stream()
.filter(e -> otherVector.containsKey(e.getKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue() * otherVector.get(e.getKey())));
如果您可以修改地图 in-place,那么您也可以遍历 otherVector
条目并相应地更新 weightedVector
地图:
otherVector.forEach((key, t) -> weightedVector.computeIfPresent(key, (k, v) -> t * v));
这将为 otherVector
中的每个键计算 otherVector
和 weightedVector
值的乘积。
我想用加权平均值做一些计算。有两张地图
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
是否是一种好习惯。
我的主要问题是我有两个输入映射并且想要获得相同类型的输出映射但是上面的代码从计算中得到了 Stream
的 Double
。
我使用 stream().collect(..)
更好吗?
不使用 HashMap
而是创建一个包含键值对的容器对象并使用它可能更好吗?
假设在没有对应条目的情况下你真的什么都不做:
Map<String, Double> result =
weightedVector.entrySet()
.stream()
.filter(e -> otherVector.containsKey(e.getKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue() * otherVector.get(e.getKey())));
如果您可以修改地图 in-place,那么您也可以遍历 otherVector
条目并相应地更新 weightedVector
地图:
otherVector.forEach((key, t) -> weightedVector.computeIfPresent(key, (k, v) -> t * v));
这将为 otherVector
中的每个键计算 otherVector
和 weightedVector
值的乘积。