0

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.

3 Answers3

2

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

Chris
  • 5,584
  • 9
  • 40
  • 58
  • 1
    I will use this with TreeMap instead of HashMap. thanks so much! – Nicolás Nistal May 25 '13 at 05:41
  • The TreeMap itself is not hassle free sorting (at least not by value). The TreeMap sorts by Key. So you will need to sort by value as a separate pass after adding all the elements with the Map approach – greedybuddha May 25 '13 at 05:58
1

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.

Dineshkumar
  • 4,165
  • 5
  • 29
  • 43
1

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.

Community
  • 1
  • 1
greedybuddha
  • 7,488
  • 3
  • 36
  • 50
  • I'm sorry, why the downvote? The answer is correct and it also has information about sorting the map afterwards to get the top n elements, which is important as a Map itself doesnt do that – greedybuddha May 25 '13 at 06:08