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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:41:48  来源:igfitidea点击:

Java 8 lambdas grouping by multiple fields

javajava-8java-streamcollectors

提问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 majorCategoryand the value is a Mapwith key minorCategoryand values is a Listof Pojoobjects 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 minorCategoryand 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?

应该工作,我想?