Я пытаюсь понять потоки Java 8. У меня есть два класса:
public class UserMeal {
protected final LocalDateTime dateTime;
protected final String description;
protected final int calories;
public UserMeal(LocalDateTime dateTime, String description, int calories) {
this.dateTime = dateTime;
this.description = description;
this.calories = calories;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public String getDescription() {
return description;
}
public int getCalories() {
return calories;
}
}
и
public class UserMealWithExceed {
protected final LocalDateTime dateTime;
protected final String description;
protected final int calories;
protected final boolean exceed;
public UserMealWithExceed(LocalDateTime dateTime, String description, int calories, boolean exceed) {
this.dateTime = dateTime;
this.description = description;
this.calories = calories;
this.exceed = exceed;
}
}
В поле exceed
указывается, будет ли сумма калорий за весь день. Это поле совпадает для всех записей за этот день.
Я пытаюсь получить объект из List<UserMeal> mealList
, группировать по дням, вычислять калории в течение определенного периода времени и создавать List<UserMealWithExceed>
:
public static List<UserMealWithExceed> getFilteredMealsWithExceeded(List<UserMeal> mealList, LocalTime startTime, LocalTime endTime, int caloriesPerDay) {
return mealList.stream()
.filter(userMeal -> userMeal.getDateTime().toLocalTime().isAfter(startTime)&&userMeal.getDateTime().toLocalTime().isBefore(endTime))
.collect(Collectors.groupingBy(userMeal -> userMeal.getDateTime().getDayOfMonth(),
Collectors.summingInt(userMeal -> userMeal.getCalories())))
.forEach( ????? );
}
но я не понимаю, как создать новый объект в forEach
и вернуть коллекцию.
Как я вижу в псевдокоде:
.foreach(
if (sumCalories>caloriesPerDay)
{return new UserMealWithExceed(userMeal.getdateTime, usermeal.getDescription, usermeal.getCalories, true);}
else
{return new UserMealWithExceed(userMeal.getdateTime, usermeal.getDescription, usermeal.getCalories, false)
}
)//foreach