Effective way to get the most used keys in HashMap - Java

I have a HashMap where the key is the word and the value is the number of occurrences of this line in the text. Now I would like to reduce this HashMap to the 15 most frequently used words (with a lot of occurrences). Do you have an idea to do this effectively?

+3
source share
4 answers

Using an array instead of an ArrayList, as suggested by Pindatjuh, might be better

public class HashTest {
        public static void main(String[] args) {
            class hmComp implements Comparator<Map.Entry<String,Integer>> {
                public int compare(Entry<String, Integer> o1,
                        Entry<String, Integer> o2) {
                    return o2.getValue() - o1.getValue();
                }
            }
            HashMap<String, Integer> hm = new HashMap<String, Integer>();
            Random rand = new Random();
            for (int i = 0; i < 26; i++) {
                hm.put("Word" +i, rand.nextInt(100));
            }
            ArrayList list = new ArrayList( hm.entrySet() );
            Collections.sort(list, new hmComp() );
            for ( int i = 0  ; i < 15 ; i++ ) {
                System.out.println( list.get(i) );
            }

        }
    }

Change EDIT Sort Order

+3
source

One way, I think, to solve this, but it is probably not the most effective:

  • Create an array hashMap.entrySet().toArray(new Entry[]{}).
  • Arrays.sort, Comparator, Entry.getValue() ( ). , .. / , / .
  • , 15- .
+2
Map<String, Integer> map = new HashMap<String, Integer>();

    // --- Put entries into map here ---

    // Get a list of the entries in the map
    List<Map.Entry<String, Integer>> list = new Vector<Map.Entry<String, Integer>>(map.entrySet());

    // Sort the list using an annonymous inner class implementing Comparator for the compare method
    java.util.Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){
        public int compare(Map.Entry<String, Integer> entry, Map.Entry<String, Integer> entry1)
        {
            // Return 0 for a match, -1 for less than and +1 for more then
            return (entry.getValue().equals(entry1.getValue()) ? 0 : (entry.getValue() > entry1.getValue() ? 1 : -1));
        }
    });

    // Clear the map
    map.clear();

    // Copy back the entries now in order
    for (Map.Entry<String, Integer> entry: list)
    {
        map.put(entry.getKey(), entry.getValue());
    }

Use the first 15 entries of the map. Or change the last 4 lines to fit only 15 records per card.

0
source

You can use LinkedHashMap and remove the least recently used items.

-1
source

Source: https://habr.com/ru/post/1736807/


All Articles