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 to Map<LocalDate, Integer> .

The map key must be the dateTime (converted to LocalDate ) of the UserMeal element in the collection.

And the value of the card should be the sum of calories .

I cannot figure out how to do this with threads. Sort of:

 items.stream().collect(Collectors.toMap(...)); 

Any help?

Here is my current code that is clearly not working.

 Map<LocalDate, Integer> values = mealList.stream() .collect(Collectors.toMap(m->m.getDateTime().toLocalDate(), m-> {/* HUH? */})); 
+5
source share
1 answer

You need another Collector :

 Map<LocalDate, Integer> values = mealList.stream() .collect(Collectors.groupingBy( m -> m.getDateTime().toLocalDate(), Collectors.summingInt(UserMeal::getCalories))); 

Or you can use Collectors.toMap , which has another argument that tells how to merge records.

+5
source

Source: https://habr.com/ru/post/1272983/


All Articles