Java 8 lambdas 按多个字段分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30808245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 lambdas grouping by multiple fields
提问by Robert Bain
I have a list of pojos that I want to perform some grouping on. Something like:
我有一个要对其进行分组的 pojo 列表。就像是:
public class Pojo {
private final Category category;
private final BigDecimal someValue;
}
public class Category {
private final String majorCategory;
private final String minorCategory;
}
I want a Map<String, Map<String, List<Pojo>>>
where the key is majorCategory
and the value is a Map
with key minorCategory
and values is a List
of Pojo
objects for said minorCategory
.
我想要一个Map<String, Map<String, List<Pojo>>>
键在哪里,majorCategory
值是一个Map
,键minorCategory
是一个List
,值是一个Pojo
对象minorCategory
。
I intend to use Java 8 lambdas to achieve this. I can get the first level of grouping done with the following:
我打算使用 Java 8 lambdas 来实现这一点。我可以通过以下方式完成第一级分组:
Map<String, Pojo> result = list
.stream()
.collect(groupingBy(p -> p.getCategory().getMajorCategory()));
How can I now group again on minorCategory
and get the Map<String, Map<String, List<Pojo>>>
I desire?
我现在怎样才能再次分组minorCategory
并获得Map<String, Map<String, List<Pojo>>>
我想要的?
Update
更新
The first answer provided is correct for the example provided initially, however I have since updated the question. Ruben's comment in the accepted answer, provides the final piece of the puzzle.
提供的第一个答案对于最初提供的示例是正确的,但是我已经更新了问题。鲁本在接受的答案中的评论提供了最后一块拼图。
回答by Louis Wasserman
groupingBy(Pojo::getMajorCategory, groupingBy(Pojo::getMinorCategory))
should work, I think?
应该工作,我想?