2017-10-29 42 views
5

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

Trả lời

5

Bạn cần một khác nhau Collector:

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

Hoặc bạn có thể sử dụng Collectors.toMap có thêm một lý lẽ mà nói làm thế nào để hợp nhất các mục.

Các vấn đề liên quan