Stephane Grenier
Stephane Grenier

Reputation: 15925

How to tabulate data grouped by month AND year using Java 8 streams

Assuming I have the simple POJO Meal:

public class Meal
{
    LocalDate mealtime;
    int calories;
}

which is then collected in a List:

List<Meals> meals;

How I can use streams to get a list that totals the calories consumed on a monthly basis over several years. It's very easy to tabulate based on the month alone but I want to create a bar chart spread over several years to compare the consumption of calories over time and NOT just by month.

How can this be done? Do I have to create some complex structure of Instant objects with months and Years using HashMaps of years and months or is there a better way?

Upvotes: 3

Views: 2556

Answers (1)

Andreas
Andreas

Reputation: 159135

You do it like this, using TreeMap to ensure that result is sorted by year and month:

Map<YearMonth, Integer> caloriesByMonth = meals.stream()
        .collect(Collectors.groupingBy(m -> YearMonth.from(m.mealtime),
                                       TreeMap::new,
                                       Collectors.summingInt(m -> m.calories)));

Upvotes: 6

Related Questions