I have the following structure:
ArrayList<ArrayList<Movies>>
And The movies have duplicates, I need to obtain the n movies that have the higher number of repetitions. I've been thinking hard on this and I can't though of any elegant solution.
I have the following structure:
ArrayList<ArrayList<Movies>>
And The movies have duplicates, I need to obtain the n movies that have the higher number of repetitions. I've been thinking hard on this and I can't though of any elegant solution.
 
    
    Change it to the following
HashMap<Movie, Integer> map = new HashMap<Movie, Integer>();
// ArrayList<ArrayList<Movies>> listOfList = ...initialized
for (ArrayList<Movie> list : listOfList)
{
   for (Movie movie : list)
   {
      if (map.containsKey(movie))
      {
         int count = map.get(movie);
         map.put(movie, (count+1));
      }
      else
      {
         map.put(movie, 1);
      }
   }
}
Make sure that you have proper implementation of hashcode and equals for this to work
 
    
    you can make use of
   Map<Movie,Integer> 
to keep
<movie,frequency>
you can search in Map or even can use TreeMap with sorting based on frequency and you can fetch first N elements from it directly.
 
    
    This is a good time to use a Map. The keys are the movie, and the values are the integer count. Afterwards you can create a new TreeMap to get the sorted values.
ArrayList<ArrayList<Movies>> myMovieList;
Map<Movie,Integer> map = new HashMap<Movie,Integer>();
for (List<Movie> movies : myMovieList) {
    for (Movie movie: movies){
        Integer count = map.get(movie);
        if (count == null){
            map.put(movie,1);
        } else {
            map.put(movie, count+1);
        }
    }
}
At the end you will have a list of Movies to their counts, and now you can sort by the values. See sorting a treemap by values, TreeMap sort by value, or you can just create a custom Class that is a movie and counter and put that into a list with a custom comparator.
 
    
    