Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by and counting comparing two arrays of objects Java

I have 3 classes: Agency, Team and Agent. An Agent belongs to a Team that belongs to an Agency.

I need to do a report counting how many agents I have on each Agency. I don't have a database, just ArrayLists with the following data:

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

On the Agent class, I have getTeam(), which has getAgency() (From Team class).

I was trying to do:

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();
            }
        }
    }
}

But I have no idea how to count it separated for each Agency.

So I tried:

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

But I can't get the agency from Agent, because I need getTeam().getAgency() and this Map doesn't allow me to do that.

Summarizing:

I have agency: A,B,C.

I have agents: X related to agency A, Y related to agency A, Z related to agency B.

I need to show: Agency A: 2 agents / Agency B: 1 agent / Agency C: 0

Can someone help me, please?

like image 895
asr Avatar asked Feb 17 '26 04:02

asr


1 Answers

You were close. You should use a lambda expression instead of method reference in this case.

This would allow you to group by a -> a.getTeam().getAgency() (or by some property of Agency having String type, since your output is a Map<String, Long>):

Map<String, Long> agentsAtAgency = 
    agents.stream()
          .filter(a -> a.getTeam() != null)
          .collect(Collectors.groupingBy(a -> a.getTeam().getAgency().getName(),
                                         Collectors.counting()));
like image 80
Eran Avatar answered Feb 19 '26 16:02

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!