I'm trying to understand Java 8 streams. I have two classes:
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;
}
}
and:
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;
}
}
The exceed
field should indicate whether the sum of calories for the entire day. This field is the same for all entries for that day.
I try to get object from List<UserMeal> mealList
, group by the day, calculate calories for a period of time, and create 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( ????? );
}
but I don't understand how to create new object in forEach
and return collection.
How I see in pseudocode:
.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
forEach
. AStream
supports more operations than this one. – Holger