我有如下的类:
public class Response {
private final Map<Integer, Double> totalListPerKey;
private final String key;
}
我得到了一个Collection<Response> responses
,它需要按键分组,并根据totalListPerKey中匹配的键(整数)对集合中所有项在映射totalListPerKey中的双精度值求和。
即
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)])
发布于 2018-08-01 05:20:19
听完你的解释
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) ) );
发布于 2018-08-01 05:28:49
您需要迭代响应的键,例如响应B,检查它是否存在于响应A中,如果存在,则将总和赋给响应A中的键的值(或其他但不是最终的键)。
编辑:如果键不存在,只需将该条目复制到最终响应中,以供将来分组。
如果你想单独保存这些值,那么你应该像这样保存一个映射
private final Map<Integer, List<Double>> totalListPerKey;
一个双精度的列表,而不仅仅是一个双精度值。
https://stackoverflow.com/questions/51621925
复制相似问题