Skip to content
Advertisement

Count Groups of Objects in List

I have a list of objects and need to count the number of objects that have the same date, location and color in Java 8:

public class Entity

  public static void main(String[] args) {

     List<Schedule> schedule = new ArrayList<Scheudle>();
     schedule.add(new Schedule("12/12/2021", "Los Angeles", "Red", "Bob"));
     schedule.add(new Schedule("12/12/2021", "Los Angeles", "Red", "Jimmy"));
     schedule.add(new Schedule("12/12/2021", "Los Angeles", "Red", "Tim"));
     schedule.add(new Schedule("12/12/2021", "Los Angeles", "Blue", "Mary"));
     schedule.add(new Schedule("12/12/2021", "Los Angeles", "Green", "Jane"));
     schedule.add(new Schedule("12/12/2021", "Los Angeles", "Green", "Jane"));
     schedule.add(new Schedule("13/12/2021", "San Deigo", "Red", "Bob"));
     schedule.add(new Schedule("13/12/2021", "San Deigo", "Green", "James"));
     schedule.add(new Schedule("13/12/2021", "San Deigo", "Green", "Anne"));
     schedule.add(new Schedule("14/12/2021", "Los Angeles", "Red", "James"));
}

So for the above the totals would be for the number of people working each combination of date, location and color. i.e.:

  • 12/12/2021 Los Angeles Red – 3
  • 12/12/2021 Los Angeles Blue – 1
  • 12/12/2021 Los Angeles Green – 2
  • 13/12/2021 San Deigo Green – 2
  • 13/12/2021 San Deigo Red – 1
  • 14/12/2021 Los Angeles Red – 1

How can this be done?

Advertisement

Answer

You can group on the three fields date, location, and color:

schedule.stream().collect(
    Collectors.groupingBy(Schedule::getDate,
        Collectors.groupingBy(Schedule::getCity,
            Collectors.groupingBy(Schedule::getColor,
                Collectors.counting()
            )
        )
    )
)

It generates the nested Map:

{
    14/12/2021={
        Los Angeles={Red=1}
    },
    13/12/2021={
        San Deigo={Red=1, Green=2}
    },
    12/12/2021={
        Los Angeles={Red=3, Blue=1, Green=2}
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement