我有一个班级的销售。
Class Sales {
String month; String year; String city; String state; String sales;
}
有一个销售对象列表
"result" :[
{
"month" : "JAN",
"year": "2000",
"state" : "State1",
"city" : "City1",
"sales" : "10"
},
{
"month" : "JAN",
"year" : "2000",
"state" : "State1",
"city" : "City2",
"sales" : "20"
},
{
"month" : "JAN",
"year" : "2000",
"state" : "State2",
"city" : "City3",
"sales" : "30",
},
{
"month" : "JAN",
"year" : "2000",
"state" : "State2",
"city" : "City1",
"sales" : "40"
},
{
"month" : "FEB",
"year" : "2000",
"state" : "State1",
"city" : "City1",
"sales" : "5",
},
{
"month" : "FEB",
"year" : "2000",
"state" : "State1",
"city" : "City2",
"sales" : "15"
}
]
现在我想要达到的是上图中描述的销售总额,我如何使用java 8实现同样的目标。我尝试了按JAVA 8的功能分组,但没有成功。
list.stream()
.collect(Collectors.groupingBy(p -> p.getMonth(), Collectors.groupingBy(p -> p.getSales(),
Collectors.summingInt(foo->foo.getTotalSales()))))
.forEach((id,total)->System.out.println(id+"\t"+total));
发布于 2020-05-04 03:35:19
您应该更改表示销售的类型。
String sales;
应该是
int sales;
或
long sales;
对于自然由数值类型表示的事物,String
不应该是该类型。
您可以使用groupingBy()
,但您应该将其应用于两个不同的流,因为您希望执行两种销售金额:按州-城市计算的销售金额(电子表格中的行)和按月计算的销售金额(电子表格中的列)。
Map<String, Integer> salesAmountByMonth =
list.stream()
.collect(groupingBy(Sale::getMonth,
summingInt(Sale::getSales)));
Map<String, Map<String,Integer>> salesAmountByStateByCity =
list.stream()
.collect(groupingBy(Sale::getState,
groupingBy(Sale::getCity,
summingInt(Sale::getSales))));
https://stackoverflow.com/questions/61579954
复制相似问题