I have a list of Maps and want to group and sum on certain columns.
List of Maps:
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);
}
I am trying to use Java 8 stream with Collectors.groupingBy and Collectors.summingDouble to get results as Map<String,Map<String,Object>>
. So far, I can get Map<String,List<Map<String,Object>>>
by using Java 8 stream with Collectors.groupingBy.
Group by "Mod" and "bigger":
Map<String, List<Map<String, Object>>> grouped = positions.stream()
.collect(
Collectors.groupingBy(m -> m.get("Mod").toString()
+ "<|>" + m.get("bigger").toString()));
Group by "Mod" and "bigger" results:
{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}]}
I am expecting Group by "Mod" and "bigger" and sum on "id" and "price" results(Map<String,Map<String,Object>>
):
{Even<|>Y={sum_price=4069.578047, sum_id=30}, Odd<|>Y={sum_price=3753.148096,sum_id=25}}
Any suggestions? Thank you,