77import java .time .LocalDateTime ;
88import java .time .LocalTime ;
99import java .time .Month ;
10- import java .util .Arrays ;
11- import java .util .List ;
12- import java .util .Map ;
10+ import java .util .*;
1311import java .util .stream .Collectors ;
1412
1513public class MealsUtil {
@@ -24,6 +22,8 @@ public static void main(String[] args) {
2422 );
2523 List <MealWithExceed > mealsWithExceeded = getFilteredWithExceeded (meals , LocalTime .of (7 , 0 ), LocalTime .of (12 , 0 ), 2000 );
2624 mealsWithExceeded .forEach (System .out ::println );
25+
26+ System .out .println (getFilteredWithExceededByCycle (meals , LocalTime .of (7 , 0 ), LocalTime .of (12 , 0 ), 2000 ));
2727 }
2828
2929 public static List <MealWithExceed > getFilteredWithExceeded (List <Meal > meals , LocalTime startTime , LocalTime endTime , int caloriesPerDay ) {
@@ -35,9 +35,25 @@ public static List<MealWithExceed> getFilteredWithExceeded(List<Meal> meals, Loc
3535
3636 return meals .stream ()
3737 .filter (meal -> TimeUtil .isBetween (meal .getTime (), startTime , endTime ))
38- .map (meal ->
39- new MealWithExceed (meal .getDateTime (), meal .getDescription (), meal .getCalories (),
40- caloriesSumByDate .get (meal .getDate ()) > caloriesPerDay ))
38+ .map (meal -> createWithExceed (meal , caloriesSumByDate .get (meal .getDate ()) > caloriesPerDay ))
4139 .collect (Collectors .toList ());
4240 }
41+
42+ public static List <MealWithExceed > getFilteredWithExceededByCycle (List <Meal > meals , LocalTime startTime , LocalTime endTime , int caloriesPerDay ) {
43+
44+ final Map <LocalDate , Integer > caloriesSumByDate = new HashMap <>();
45+ meals .forEach (meal -> caloriesSumByDate .merge (meal .getDate (), meal .getCalories (), Integer ::sum ));
46+
47+ final List <MealWithExceed > mealsWithExceeded = new ArrayList <>();
48+ meals .forEach (meal -> {
49+ if (TimeUtil .isBetween (meal .getTime (), startTime , endTime )) {
50+ mealsWithExceeded .add (createWithExceed (meal , caloriesSumByDate .get (meal .getDate ()) > caloriesPerDay ));
51+ }
52+ });
53+ return mealsWithExceeded ;
54+ }
55+
56+ public static MealWithExceed createWithExceed (Meal meal , boolean exceeded ) {
57+ return new MealWithExceed (meal .getDateTime (), meal .getDescription (), meal .getCalories (), exceeded );
58+ }
4359}
0 commit comments