Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? */}));
like image 421
Philip Avatar asked Oct 29 '17 21:10

Philip


1 Answers

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.

like image 89
Eugene Avatar answered Nov 11 '22 14:11

Eugene