集合实体中的多重分组和排序

jhdbpxl9  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(264)

我有如下实体-

@Entity
public class Certification {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String role;  // can have values like "Architect", "Developer", "Business Practioner"
    private int score;
    private Date expiryDate

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "solution_id")
    private Solution solution;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "region_id")
    private Region region;
}

@Entity
public class Solution {
  private String name;  //can have values like "Analytics", "Campaign", "Marketo"
}

@Entity
public class Region{
    private String name;  //can have values like "EMEA", "APAC", "JAPAN" & "AMERICAS"
}

@Entity
public class Employee {
@OnetoMany(fetch = FetchType.LAZY)
    private List<Certification> certifications
}

拉取员工证书后,我需要进行多次分组和排序,然后拉取特定角色下的证书计数。首先我按解决方案名称分组,然后按区域分组,然后按角色分组。每个组都需要按字母顺序排序。例如,在解决方案组下,“分析”应该排在“活动”的前面。在“亚太地区”之下,应该先是“欧洲、中东和非洲”。在角色组中,“架构”应该排在“业务实践者”之后。

{
  "expertise": [
    {
      "solutionName": "Analytics",
      "regions": [
        {
          "name": "APAC",
          "roles": [
            {
              "name": "Architect",
              "certifiedEmployees": 12
            },
            {
              "name": "Business Practitioner",
              "certifiedEmployees": 9
            }
          ]
        },
        {
          "name": "EMEA",
          "roles": [
            {
              "name": "Architect",
              "certifiedEmployees": 12
            }
          ]
        }
      ]
    },
    {
      "solutionName": "Campaign",
      "regions": [
        {
          "name": "APAC",
          "roles": [
            {
              "name": "Architect",
              "certifiedEmployees": 12
            },
            {
              "name": "Business Practitioner",
              "certifiedEmployees": 9
            }
          ]
        },
        {
          "name": "EMEA",
          "roles": [
            {
              "name": "Architect",
              "certifiedEmployees": 12
            },
            {
              "name": "Back-end Developer",
              "certifiedEmployees": 9
            }
          ]
        }
      ]
    }
  ]
}

我尝试使用collectors.groupingby和comparator.comparing,但未能达到预期效果。

yvgpqqbh

yvgpqqbh1#

找到了一种使用java流和groupingby对列表进行分组的更好方法。它很短,可以帮助我避免很多代码

credentials.stream().collect(groupingBy(c -> c.getSolution().getName(), groupingBy(c -> c.getRegion().getName())));

相关问题