Tôi có một bộ sưu tập List<UserMeal>
, nơi UserMeal có:Collectors.toMap() keyMapper
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;
}
}
tôi cần phải chuyển đổi nó thành Map<LocalDate, Integer>
.
Khóa của bản đồ phải là dateTime
(được chuyển đổi thành LocalDate
) của mục UserMeal trong bộ sưu tập.
Và giá trị của bản đồ phải bằng tổng là calories
.
Tôi không thể tìm ra cách thực hiện điều này bằng luồng. Một cái gì đó như:
items.stream().collect(Collectors.toMap(...));
Bất kỳ trợ giúp nào?
Đây là mã hiện tại của tôi rõ ràng không hoạt động.
Map<LocalDate, Integer> values = mealList.stream()
.collect(Collectors.toMap(m->m.getDateTime().toLocalDate(),
m-> {/* HUH? */}));