【问题标题】:Group by and counting comparing two arrays of objects Java分组和计数比较两个对象数组Java
【发布时间】:2018-05-13 08:36:50
【问题描述】:

我有 3 个课程:AgencyTeamAgentAgent 属于 Team,而 Team 又属于 Agency

我需要做一份报告,计算每个 Agency 上我有多少代理。 我没有数据库,只有ArrayLists 有以下数据:

List<Agent> agents
List<Team> teams
List<Agency> agencies

Agent 类上,我有getTeam(),它有getAgency()(来自Team 类)。

我想这样做:

for (Agency ag : agencies) {
    for (Agent a : agents) {
        if (a.getTeam() != null) {
            if (a.getTeam().getAgency() == ag) {
               teste = "Agency from agent" + a.getTeam().getAgency().getCode() + "Agency from agency" + ag.getCode();
            }
        }
    }
}

但我不知道如何将每个 Agency 分开计算。

所以我尝试了:

Map<String, Long> agentsAtAgency = 
    agents.stream()
          .collect(Collectors.groupingBy(Agent::getTeam, Collectors.counting()));

但我无法从Agent 获得代理,因为我需要getTeam().getAgency() 而这张地图不允许我这样做。

总结:

我有代理:A、B、C。

我有代理:X 与代理 A 相关,Y 与代理 A 相关,Z 与代理 B 相关。

我需要出示:A 机构:2 名代理人/B 机构:1 名代理人/C 机构:0 人

有人可以帮帮我吗?

【问题讨论】:

    标签: java group-by java-8 counting collectors


    【解决方案1】:

    你很亲密。在这种情况下,您应该使用 lambda 表达式而不是方法引用。

    这将允许您按a -&gt; a.getTeam().getAgency()(或Agency 具有String 类型的某些属性进行分组,因为您的输出是Map&lt;String, Long&gt;):

    Map<String, Long> agentsAtAgency = 
        agents.stream()
              .filter(a -> a.getTeam() != null)
              .collect(Collectors.groupingBy(a -> a.getTeam().getAgency().getName(),
                                             Collectors.counting()));
    

    【讨论】:

    • 请问如何将值作为字符串返回?如果我想为每个代理显示“代理 x 有 y 代理”
    • @asr 我假设Agency 有一个getName() 属性(或类似的属性),它返回一个String。您可以遍历输出 Map 的条目并以您喜欢的任何格式打印它们。
    • 我收到空指针异常,因为并非我的所有代理都有团队。这不是循环,如何过滤 if (agent.getTeam != null) ?
    • @asr for (Map.Entry&lt;String,Long&gt; entry : agentsAtAgency) {System.out.println("Agency " + entry.getKey() + " has " + entry.getValue() + " agents");}
    • agentsAtAgency.forEach( (agency,count) -&gt; System.out.println("Agency "+agency+" has " +count+" agents" );
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2011-10-02
    • 2020-01-17
    • 1970-01-01
    相关资源
    最近更新 更多