使用Java流分组后,如何在列表中对象的Map<Integer,Double>中对双精度求和



我有以下类:

public class Response {
private final Map<Integer, Double> totalListPerKey;
private final String key;
}

我得到了一个Collection<Response> responses,它需要按键分组,并根据totalListPerKey中的匹配键(Integer(对集合中所有项的映射totalListPermKey中的Double值求和。

Response A = new Response(new HashMap[(1234,325.3),(2345,123.5)],test)
Response B = new Response(new HashMap[(1234,454.3),(2345,50)],test)

预期结果:

Object(test,new HashMap[(1234,779.6),(2345,173.5)])

您需要迭代响应的键,比如响应B,检查它是否存在于响应a中,如果存在,则将总和分配给响应a中该键的值(或其他但最终的值(。

编辑:如果键不存在,只需将条目复制到最终响应中,以便将来分组。

如果你想单独保存这些值,那么你应该保存一个类似的地图

private final Map<Integer, List<Double>> totalListPerKey;是一个双精度的列表,而不是只有一个双值。

在您解释之后

Map<Integer, Set<Double>> collectSetOfDoublesByIntKey = objsWithIntAndDouble.stream().collect( Collectors.groupingBy(Obj::getInt, Collectors.mapping(Obj::getDouble, Collectors.toSet()) ) );
Map<Integer, Double> collectSumOfDoublesByIntKey = objsWithIntAndDouble.stream().collect( Collectors.groupingBy(Obj::getInt, Collectors.summingDouble(Obj::getDouble) ) );