首页 > 解决方案 > 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.:

How can this be done?

标签: java

解决方案


Try this.

record Schedule(String date, String location, String color, String name) {}
List<Schedule> schedule = new ArrayList<Schedule>();
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"));
record ScheduleGroup(String date, String location, String color) {}
Map<ScheduleGroup, Long> groups = schedule.stream()
    .collect(Collectors.groupingBy(
        s -> new ScheduleGroup(s.date(), s.location(), s.color()),
        Collectors.counting()));
for (Entry<ScheduleGroup, Long> g : groups.entrySet())
    System.out.println(g);

output:

ScheduleGroup[date=13/12/2021, location=San Deigo, color=Green]=2
ScheduleGroup[date=12/12/2021, location=Los Angeles, color=Blue]=1
ScheduleGroup[date=14/12/2021, location=Los Angeles, color=Red]=1
ScheduleGroup[date=13/12/2021, location=San Deigo, color=Red]=1
ScheduleGroup[date=12/12/2021, location=Los Angeles, color=Green]=2
ScheduleGroup[date=12/12/2021, location=Los Angeles, color=Red]=3

推荐阅读