问题
I have a class Sales.
Class Sales {
String month; String year; String city; String state; String sales;
}
Have a list of Sales objects
"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"
}
]
Now what I trying to achieve is the total of sales like depicted in above picture, how can i achieve the same using java 8. I tried grouping by JAVA 8 features, but no luck.
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));
回答1:
You should change the type representing the sales.
String sales;
should be
int sales;
or
long sales;
String
should not be the type for things that are naturally represented by numeric types.
You could use groupingBy()
but you should apply that on two distinct streams because you want to perform two kind of sales sums : a sales sum by state-city (row in your spreadsheet) and a sales sum by month (column in your spreadsheet).
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/java-8-pojo-objects-filter-pojo-based-on-common-multiple-key-combination-and-sum