如何在Map中求和双倍<;整数,双精度>;使用Java流分组后列表中对象的
我有以下课程:如何在Map中求和双倍<;整数,双精度>;使用Java流分组后列表中对象的,java,java-8,java-stream,Java,Java 8,Java Stream,我有以下课程: public class Response { private final Map<Integer, Double> totalListPerKey; private final String key; } 预期结果: Object(test,new HashMap[(1234,779.6),(2345,173.5)]) 听你的解释 Map<Integer, Set<Double>> collectSetOfDouble
public class Response {
private final Map<Integer, Double> totalListPerKey;
private final String key;
}
预期结果:
Object(test,new HashMap[(1234,779.6),(2345,173.5)])
听你的解释
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) ) );
Map collectSetOfDoublesByIntKey=objsWithIntAndDouble.stream().collect(Collectors.groupingBy(Obj::getInt,Collectors.mapping(Obj::getDouble,Collectors.toSet());
Map collectSumOfDoublesByIntKey=objsWithInAndDouble.stream().collect(Collectors.groupingBy(Obj::getInt,Collectors.summingDouble(Obj::getDouble));
您需要对响应的键进行迭代,比如说响应B,检查它是否存在于响应a中,如果存在,则将总和分配给响应a中该键的值(或其他但最终的值)
编辑:如果密钥不存在,只需将条目复制到最终响应,以便将来分组
如果您想单独保留这些值,那么应该像
private final Map totalistperkey代码>一个双精度列表,而不是一个双精度值。我试图解决的问题是,我有一个对象列表,其中包含一个键和映射字符串。这更复杂,因为我需要用匹配的键对对象列表进行分组,然后在地图列表中对每个项加上双精度。所以你的答案并没有真正的帮助。你必须按键对列表进行分组,然后对每个对象进行汇总,并将它们分开,或者将它们全部从列表中删除?保持它们分开
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) ) );