You need to use the Map.Entry<String, Integer>
to get the pair of the key and value.
The values()
method returns only values, whereas the keySet()
method returns only the keys.
Firstly, you should sort your map, based on values, to get the top five results.
The straightforward approach uses a Comparator
. See the answer here for more.
Then you simply get the first five entries of the map.getEntrySet()
. It would be easier to use an Iterator
for this.
UPDATE:
Set<Entry<String, Integer>> set = wordCount.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
int topResults = 5;
Iterator<Entry<String, Integer>> iter = list.iterator(); //refer the sorted collection
while (iter.hasNext() && topResults > 0 ) {
Map.Entry<String, Integer> entry = iter.next();
System.out.println(entry.getKey() + "->" + entry.getValue());
topResults --;
}