【发布时间】:2015-07-10 00:06:45
【问题描述】:
我有一个地图列表,想对某些列进行分组和求和。
地图列表:
double min=100;
double max=999;
List<Map<String,Object>> positions = new ArrayList<Map<String,Object>>();
for (int i=0; i<10; i++) {
Map<String,Object> positionRow = new HashMap<String,Object>();
positionRow.put("id", i+1);
if ((i+1)%2 == 0)
positionRow.put("Mod", "Even");
else
positionRow.put("Mod", "Odd");
Random r = new Random();
double randomValue = min + (max - min) * r.nextDouble();
positionRow.put("price", randomValue);
positionRow.put("bigger", (randomValue > 300)?"Y":"N");
positions.add(positionRow);
}
我正在尝试将 Java 8 流与 Collectors.groupingBy 和 Collectors.summingDouble 一起使用,以获得Map<String,Map<String,Object>> 的结果。到目前为止,我可以通过使用带有 Collectors.groupingBy 的 Java 8 流获得Map<String,List<Map<String,Object>>>。
按“Mod”和“更大”分组:
Map<String, List<Map<String, Object>>> grouped = positions.stream()
.collect(
Collectors.groupingBy(m -> m.get("Mod").toString()
+ "<|>" + m.get("bigger").toString()));
按“Mod”和“更大”结果分组:
{Even<|>Y=[{Mod=Even, price=872.729803251601, bigger=Y, id=2}, {Mod=Even, price=353.6589309614915, bigger=Y, id=4}, {Mod=Even, price=981.8179976373482, bigger=Y, id=6}, {Mod=Even, price=942.3538966530067, bigger=Y, id=8}, {Mod=Even, price=919.0174189044218, bigger=Y, id=10}], Odd<|>Y=[{Mod=Odd, price=663.7589137270676, bigger=Y, id=1}, {Mod=Odd, price=894.1766799283644, bigger=Y, id=3}, {Mod=Odd, price=905.8003509608488, bigger=Y, id=5}, {Mod=Odd, price=758.3085768816934, bigger=Y, id=7}, {Mod=Odd, price=531.1035747782346, bigger=Y, id=9}]}
我期待 Group by "Mod" 和 "bigger" 和 sum on "id" 和 "price" 结果(Map<String,Map<String,Object>>):
{Even<|>Y={sum_price=4069.578047, sum_id=30}, Odd<|>Y={sum_price=3753.148096,sum_id=25}}
有什么建议吗?谢谢,
【问题讨论】:
标签: lambda java-8 java-stream