11import java .util .ArrayList ;
2+ import java .util .HashMap ;
23
34/**
45 * Week2. A new class to do many of the calculations focusing on computing averages on movie
@@ -11,6 +12,7 @@ public class SecondRatings {
1112 private final ArrayList <Movie > myMovies ;
1213 private final ArrayList <Rater > myRaters ;
1314 private final FirstRatings firstRatings ;
15+ private final HashMap <String , ArrayList <Double >> moviesAndRatings ;
1416
1517 public SecondRatings () {
1618 // default constructor
@@ -24,6 +26,27 @@ public SecondRatings(String moviesFileName, String ratingsFileName) {
2426 firstRatings = new FirstRatings (moviesFileName , ratingsFileName );
2527 myMovies = firstRatings .getMovieArrayList ();
2628 myRaters = firstRatings .getRaterArrayList ();
29+ moviesAndRatings = getMoviesAndRatingsMap ();
30+ }
31+
32+ // Returns a Map with movieID and all its ratings
33+ private HashMap <String , ArrayList <Double >> getMoviesAndRatingsMap () {
34+ HashMap <String , ArrayList <Double >> map = new HashMap <>();
35+
36+ for (Movie movie : myMovies ) {
37+ map .putIfAbsent (movie .getID (), new ArrayList <>());
38+ }
39+
40+ for (Rater rater : myRaters ) {
41+ ArrayList <String > ratings = rater .getItemsRated ();
42+ for (String movieID : ratings ) {
43+ // String movieID, double rating
44+ ArrayList <Double > list = map .get (movieID );
45+ list .add (rater .getRating (movieID ));
46+ }
47+ }
48+
49+ return map ;
2750 }
2851
2952 /**
@@ -45,4 +68,20 @@ public int getMovieSize() {
4568 public int getRaterSize () {
4669 return this .firstRatings .getRatersNumber ();
4770 }
71+
72+ /*
73+ This method returns a double representing the average movie rating for this ID
74+ if there are at least minimalRaters ratings.
75+ If there are not minimalRaters ratings, then it returns 0.0.
76+ */
77+ private Double getAverageByID (String id , Integer minimalRaters ) {
78+ double result = 0.0 ;
79+ ArrayList <Double > ratings = moviesAndRatings .get (id );
80+ if (ratings != null && ratings .size () >= minimalRaters ) {
81+ result = ratings .stream ().mapToDouble (d -> d ).average ().orElse (0.0 );
82+ }
83+
84+ // If there are no ratings returns 0.0
85+ return result ;
86+ }
4887}
0 commit comments