简体   繁体   English

Java 8 lambdas按多个字段分组

[英]Java 8 lambdas grouping by multiple fields

I have a list of pojos that I want to perform some grouping on. 我有一个pojos列表,我想要执行一些分组。 Something like: 就像是:

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 ,值是带有键minorCategoryMap ,值是所述minorCategoryPojo对象List

I intend to use Java 8 lambdas to achieve this. 我打算用Java 8 lambdas来实现这一点。 I can get the first level of grouping done with the following: 我可以通过以下方式完成第一级分组:

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进行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. 鲁本在接受的答案中的评论提供了最后一块拼图。

groupingBy(Pojo::getMajorCategory, groupingBy(Pojo::getMinorCategory))

应该工作,我想?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM