我正在尝试理解 Java8流。 我有两门课:
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