I have been given a large text as input. I have made a HashMap that stores each different word as a key, and number of times that occurs as value (Integer).
Now I have to make a method called mostOften(int k):List that return a List that gives the first k-words that from max number of occurrence to min number of occurrence ( descending order ) using the HashMap that I have made before. The problem is that whenever 2 words have the same number of occurrence, then they should be sorted alphabetically.
The first idea that was on my mind was to swap keys and values of the given HashMap, and put it into TreeMap and TreeMap will sort the words by the key(Integer - number of occurrence of the word ) and then just pop the last/first K-entries from the TreeMap.
But I will have collision for sure, when the number of 2 or 3 words are the same. I will compare the words alphabetically but what Integer should I put as a key of the second word comming.
Any ideas how to implement this, or other options ?
Here's the solution with I come up.
MyWord
that can store theString
value of the word and the number of occurences it appears.Comparable
interface for this class to sort by occurences first and then alphabetically if the number of occurences is the sameList
ofMyWord
from your originalmap
. You add the entries of this to yourList
subList
Strings
to theList<String>
and you return itOutput :
[halo, hello, that]