Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
分组和计数比较两个Java对象数组_Java_Group By_Java 8_Counting_Collectors - Fatal编程技术网

分组和计数比较两个Java对象数组

分组和计数比较两个Java对象数组,java,group-by,java-8,counting,collectors,Java,Group By,Java 8,Counting,Collectors,我有三门课:代理,团队和代理。代理属于属于代理的团队 我需要做一份报告,统计我在每个机构中有多少代理。 我没有数据库,只有ArrayLists和以下数据: List<Agent> agents List<Team> teams List<Agency> agencies 但我不知道如何为每个机构分别计算 所以我试着: Map<String, Long> agentsAtAgency = agents.stream()

我有三门课:
代理
团队
代理
代理
属于属于
代理
团队

我需要做一份报告,统计我在每个
机构中有多少代理。
我没有数据库,只有
ArrayList
s和以下数据:

List<Agent> agents
List<Team> teams
List<Agency> agencies
但我不知道如何为每个
机构
分别计算

所以我试着:

Map<String, Long> agentsAtAgency = 
    agents.stream()
          .collect(Collectors.groupingBy(Agent::getTeam, Collectors.counting()));
Map agentsagency=
agent.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


有人能帮帮我吗?

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

这将允许您按
a->a.getTeam().getAgency()
(或者按
Agency
具有
String
类型的属性进行分组,因为您的输出是一个
Map
):

Map agentsagency=
agent.stream()
.filter(a->a.getTeam()!=null)
.collect(收集器.groupingBy(a->a.getTeam().getAgency().getName(),
收集器。计数();

如何以字符串形式返回值?如果我想为每个代理显示“代理x有y个代理”@asr,我假设
代理
有一个
getName()
属性(或类似属性),返回一个
字符串
。您可以迭代输出映射的条目,并以您喜欢的任何格式打印它们。这不是一个循环,如果(agent.getTeam!=null)@asr
for(Map.Entry条目:agentsAtAgency){System.out.println(“Agency”+Entry.getKey()+“has”+Entry.getValue()+“agents”);}
agentsAtAgency.forEach((Agency,count)->System.out.println(“Agency”+Agency+“has”+count+“Agency”;
Map<String, Long> agentsAtAgency = 
    agents.stream()
          .collect(Collectors.groupingBy(Agent::getTeam, Collectors.counting()));
Map<String, Long> agentsAtAgency = 
    agents.stream()
          .filter(a -> a.getTeam() != null)
          .collect(Collectors.groupingBy(a -> a.getTeam().getAgency().getName(),
                                         Collectors.counting()));