Advertisement
mauricioribeiro

Java Movie Test

Sep 8th, 2020
2,329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. package com.#.movies;
  2.  
  3. import java.util.*;
  4. import java.util.stream.Collectors;
  5.  
  6. public class MoviesAnalyzer {
  7.  
  8.     static class Movie {
  9.         String title;
  10.         String duration;
  11.         List<String> actors;
  12.         List<Integer> watchlist;
  13.         List<Integer> favorites;
  14.         List<Rating> ratings;
  15.     }
  16.  
  17.     static class Rating {
  18.         int userId;
  19.         int rating;
  20.     }
  21.  
  22.     static class User {
  23.         int userId;
  24.         String email;
  25.         List<Integer> friends;
  26.     }
  27.  
  28.     List<Movie> movies;
  29.  
  30.     List<User> users;
  31.  
  32.     public MoviesAnalyzer(List<Movie> movies, List<User> users) {
  33.         this.movies = movies;
  34.         this.users = users;
  35.     }
  36.  
  37.     public List<String> topFavouriteMoviesAmongFriends(int userId) {
  38.  
  39.         List<String> movies = new ArrayList<>();
  40.         HashMap<String, Long> ranking = new HashMap<>();
  41.         Optional<User> user = findUser(userId);
  42.  
  43.         user.ifPresent(u -> this.movies.stream().forEach(movie -> {
  44.             Long friendsRating = movie.favorites.stream()
  45.                     .filter(favorite -> u.friends.contains(favorite)).count();
  46.             ranking.put(movie.title, friendsRating);
  47.         }));
  48.  
  49.         ranking.entrySet().stream()
  50.                 .sorted(Map.Entry.comparingByKey())
  51.                 .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
  52.                 .forEach(r -> movies.add(r.getKey()));
  53.  
  54.  
  55.         return movies.subList(0, 3);
  56.     }
  57.  
  58.     private Optional<User> findUser(int userId) {
  59.         for(int i = 0; i < this.users.size(); i++) {
  60.             if (this.users.get(i).userId == userId) {
  61.                 return Optional.of(this.users.get(i));
  62.             }
  63.         }
  64.         return Optional.empty();
  65.     }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement