88import java .time .LocalTime ;
99import java .time .Month ;
1010import java .util .*;
11+ import java .util .stream .Collectors ;
1112
1213public class UserMealsUtil {
1314 public static void main (String [] args ) {
@@ -23,8 +24,8 @@ public static void main(String[] args) {
2324
2425 List <UserMealWithExcess > mealsTo = filteredByCycles (meals , LocalTime .of (7 , 0 ), LocalTime .of (12 , 0 ), 2000 );
2526 mealsTo .forEach (System .out ::println );
26-
27- // System.out.println(filteredByStreams(meals, LocalTime.of(7, 0), LocalTime.of(12, 0), 2000));
27+ System . out . println ( "--------------------------------------------" );
28+ System .out .println (filteredByStreams (meals , LocalTime .of (7 , 0 ), LocalTime .of (12 , 0 ), 2000 ));
2829 }
2930
3031 public static List <UserMealWithExcess > filteredByCycles (List <UserMeal > meals , LocalTime startTime , LocalTime endTime , int caloriesPerDay ) {
@@ -36,14 +37,22 @@ public static List<UserMealWithExcess> filteredByCycles(List<UserMeal> meals, Lo
3637 for (UserMeal meal : meals ) {
3738 LocalDateTime dateTime = meal .getDateTime ();
3839 if (TimeUtil .isBetweenHalfOpen (dateTime .toLocalTime (), startTime , endTime )) {
39- userMealWithExcesses .add (new UserMealWithExcess (meal . getDateTime (), meal . getDescription () ,
40- meal . getCalories (), caloriesSumPerDate .get (dateTime .toLocalDate ()) > caloriesPerDay ));
40+ userMealWithExcesses .add (createUserWithExcess (meal ,
41+ caloriesSumPerDate .get (meal . getDateTime () .toLocalDate ()) > caloriesPerDay ));
4142 }
4243 }
4344 return userMealWithExcesses ;
4445 }
4546
4647 public static List <UserMealWithExcess > filteredByStreams (List <UserMeal > meals , LocalTime startTime , LocalTime endTime , int caloriesPerDay ) {
47- return null ;
48+ Map <LocalDate , Integer > caloriesSumPerDate = meals .stream ().collect (Collectors .groupingBy (meal -> meal .getDateTime ().toLocalDate (),
49+ Collectors .summingInt (UserMeal ::getCalories )));
50+ return meals .stream ().filter (meal -> TimeUtil .isBetweenHalfOpen (meal .getDateTime ().toLocalTime (), startTime , endTime ))
51+ .map (meal -> createUserWithExcess (meal , caloriesSumPerDate .get (meal .getDateTime ().toLocalDate ()) > caloriesPerDay ))
52+ .collect (Collectors .toList ());
53+ }
54+
55+ public static UserMealWithExcess createUserWithExcess (UserMeal meal , boolean excess ) {
56+ return new UserMealWithExcess (meal .getDateTime (), meal .getDescription (), meal .getCalories (), excess );
4857 }
4958}
0 commit comments