Philip
Philip

Reputation: 121

Collectors.toMap() keyMapper

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? */}));

Upvotes: 5

Views: 662

Answers (1)

Eugene
Eugene

Reputation: 121028

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.

Upvotes: 5

Related Questions