I have a List<UserMeal>
collection, where UserMeal has:
public class UserMeal {
private final LocalDateTime dateTime;
private final int calories;
public UserMeal(LocalDateTime dateTime, int calories) {
this.dateTime = dateTime;
this.calories = calories;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public int getCalories() {
return calories;
}
}
I need to convert it into Map<LocalDate, Integer>
.
The key of the map must be the dateTime
(converted to LocalDate
) of the UserMeal item in the collection.
And the value of the map has to be sum of calories
.
I can not figure it out how to do this with streams. Something like:
items.stream().collect(Collectors.toMap(...));
Any help?
Here's my current code which obviously doesn't work.
Map<LocalDate, Integer> values = mealList.stream()
.collect(Collectors.toMap(m->m.getDateTime().toLocalDate(),
m-> {/* HUH? */}));
You need a different Collector
:
Map<LocalDate, Integer> values = mealList.stream()
.collect(Collectors.groupingBy(
m -> m.getDateTime().toLocalDate(),
Collectors.summingInt(UserMeal::getCalories)));
Or you could use Collectors.toMap
that has one more argument that tells how to merge entries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With