The solution I chose was to first create a hash map with pairs of key values. I got the score by sorting through a linked list and inserting a pair of key values. Before inserting, I would check the existence and increase the score. This part was pretty straight forward.
In the next part, where I needed to sort it according to its value, I used the guava library published by google, and it was very easy to sort by value instead of a key, using what they called a multimap. where they, in a sense, reverse the hash and allow you to display multiple values ββon one key, so that I can have all of my first 1000, the opposite of some of the solutions mentioned above, which would not allow this, and would make me just get one value for each key.
The last step was to iterate over the multimap (back) to get the 1000 most common cases.
Look at the function code if you are interested.
private static void FindNMostFrequentOccurences(ArrayList profileName,int n) { HashMap<String, Integer> hmap = new HashMap<String, Integer>(); //iterate through our data for(int i = 0; i< profileName.size(); i++){ String current_id = profileName.get(i).toString(); if(hmap.get(current_id) == null){ hmap.put(current_id, 1); } else { int current_count = hmap.get(current_id); current_count += 1; hmap.put(current_id, current_count); } } ListMultimap<Integer, String> multimap = ArrayListMultimap.create(); hmap.entrySet().forEach(entry -> { multimap.put(entry.getValue(), entry.getKey()); }); for (int i = 0; i < n; i++){ if (!multimap.isEmpty()){ int lastKey = Iterables.getLast(multimap.keys()); String lastValue = Iterables.getLast(multimap.values()); multimap.remove(lastKey, lastValue); System.out.println(i+1+": "+lastValue+", Occurences: "+lastKey); } } }
source share