0

My Spring boot back end manage apps and games. I have Rating Object and in this rating object and save rating history in an HashMap

// Number of history by day
@ElementCollection(fetch = FetchType.EAGER)
private Map<String, Integer> ratingHistory = new HashMap<>();

I will have something like :

"ratingHistory": {
  "07/01/2020": 12,
  "07/02/2020": 5,
  "07/03/2020": 0
}

This json will grow...

I want to display a chart showing the evolution of the rating for: this week : I will return the 7 last data in my hashmap enter image description here

How could I aggregate and return processed data when I want to display:

  • last 30 days rating evolution (I want to show week 1 (sum of all days of this week), week 2, week3, week 4)
  • last 3 months (May(sum of all days of this month), June, July)
  • from the beginning of the app...

I have no idea about how to correctly handle it. Thanks

Teddy Kossoko
  • 1,168
  • 3
  • 20
  • 48

1 Answers1

2

Assuming you're using Java 8+, you should change the Map<String, Integer> to a NavigableMap<LocalDate, Integer>, which in reality will be a TreeMap.

This ensures that the keys are sortable, allowing you to call subMap(LocalDate from, LocalDate to), which will help once the map grows very large.

Also, the use of LocalDate makes it easier to group by:

As for how to do the actual aggregation using Java 8+ Streams, there are lots of examples of that on the web, using collect(Collectors.groupingBy(...)), e.g. Group by and sum objects like in SQL with Java lambdas?.

Andreas
  • 154,647
  • 11
  • 152
  • 247