Reputation: 1322
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
How could I aggregate and return processed data when I want to display:
I have no idea about how to correctly handle it. Thanks
Upvotes: 0
Views: 462
Reputation: 159135
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:
Week: WeekFields.of(Locale.US)
, and the 2 methods weekBasedYear()
and weekOfWeekBasedYear()
.
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?.
Upvotes: 2