Im using the following code to create a hashmap and then sort the values in the hashmap by using a treemap and a comparator. However, the output is rather unexpected. So any th
What you are doing is really a misuse of tools.
I believe what you need to do is:
Of course you can still make use of something like a TreeSet and use frequency as key, but you should have list of words as the value of this map (aka Multi-Map), instead of writing a problematic comparator which do not follow the contract of Comparator: http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html#compare%28T,%20T%29 Both your original implementation and the one in comment of one of the answers does not comply with the rule of sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y
(The original one is even worse).
some code snippet just for giving you hints:
List words = ....;
Map wordFrequencyMap = new HashMap();
// iterate words and update wordFrequencyMap accordingly
List uniqueWords = new ArrayList(new HashSet(words));
Collections.sort(uniqueWords, new WordFrequencyComparator(wordFrequencyMap));
for (String w : uniqueWords) {
System.out.println("word : " + w + " frequency : " + wordFrequencyMap.get(w));
}
The missing part shouldn't be anything difficult.