Aggregate data by date in java stream

Vincent Passau :

I have a List of StatisticsItem (String context, Integer numberOfHits, String yyyyMM). An example of instance is context=WEBSITE, numberOfHits=12456, yyyyMM="2019-06".

I want to get a sorted Map<String, Integer> which has as key the yyyyMM date and as value the aggregated number of hits for this month.

I try this kind of code but I can't fill the blanks :

Map<String, Integer> collect = 
      list.stream()
          .sorted((s1, s2) -> s1.getYearAndMonth().compareTo(s2.getYearAndMonth()))
          ./* TODO: What method ? */((s1, s2) -> s1.getYearAndMonth().equals(s2.getYearAndMonth())
            ? new StatisticsItem(s1.getNumberOfHits() + s2.getNumberOfHits(), s1.getYearAndMonth()) // Construct new StatistictsItem without "context"
            : /* TODO: don't touch data with different dates */)
    .collect(Collectors.toMap(s -> s.getYearAndMonth(), s -> s.getNumberOfHits()));

Input :

{context="WEBSITE", numberOfHits=500, yyyyMM="2019-04", 
context="WEBSITE", numberOfHits=750, yyyyMM="2019-05", 
context="WEBSITE", numberOfHits=470, yyyyMM="2019-06",
context="REST", numberOfHits=5400, yyyyMM="2019-04", 
context="REST", numberOfHits=4700, yyyyMM="2019-05", 
context="REST", numberOfHits=9700, yyyyMM="2019-06"}

Desired output (context can be null or whatever else in this case) :

{context=null, numberOfHits=5900, yyyyMM="2019-04", 
context=null, numberOfHits=5450, yyyyMM="2019-05", 
context=null, numberOfHits=10170, yyyyMM="2019-06"}
daniu :

You can just group by the date field.

list.stream().groupingBy(StatisticsItem::getYyyyMM, 
              Collectors.mapping(StatisticsItem::getNumberOfHits, Collectors.summingInt(Integer::intValue)))

Then you have a Map<String, Integer> with [yyyyMM - count] entries.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121748&siteId=1