kwolff7 kwolff7 - 6 months ago 6x
Java Question

Finding the Key from Value in Map

So I am having a bit of trouble understanding how to do this. I am building a word counter in Java using

Map<String, Integer>
where a word is the
and the amount of times that word was said in a .txt document is
. This is all working great...but I am trying to develop a part where it will display at the bottom what the top 5 results are ---> what the top 5

The problem I have run into is after I find the value, I can't get the String with it.

Any suggestions would be very helpful to me.


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.


    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 =;
        System.out.println(entry.getKey() + "->" + entry.getValue());
        topResults --;