Java 8 Java8POJO对象基于公共多键组合和一个字段上的和过滤POJO

Java 8 Java8POJO对象基于公共多键组合和一个字段上的和过滤POJO,java-8,Java 8,我有一个班级 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", "st

我有一个班级

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"
}
]

现在我想要达到的是上图所示的销售总额,我如何使用Java8实现同样的销售总额呢。我试着按照Java8特性进行分组,但没有成功

    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));

您应该更改表示销售的类型

String sales;
应该是

int sales;

String
不应该是自然由数字类型表示的类型

您可以使用
groupingBy()
,但您应该将其应用于两个不同的流,因为您希望执行两种类型的销售总额:按州-城市的销售总额(电子表格中的行)和按月的销售总额(电子表格中的列)

映射salesAmountByMonth=
list.stream()
.collect(分组依据)(销售::getMonth,
汇总(销售::getSales));
地图salesAmountByStateByCity=
list.stream()
.collect(分组依据)(销售::getState,
groupingBy(销售::getCity,
汇总(销售::getSales));

谢谢@davidxxx salesAmountByMonth运行良好salesAmountByCity没有什么问题,它给了我70…因为city1在两个州都有。我想我应该分州和市两个组别that@vidyashi不客气,您对地理条件的嵌套分组也是正确的。你有几种方法可以做到这一点。我用其中一个进行了编辑。谢谢@davidxxx。你也能看一下吗
long sales;
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))));