How to get the top 10 keys in descending order of their values ​​for the map <String, Integer>

map.put("Tom",5);
map.put("Tim",2);
map.put("Ted",4);

And then I could broadcast it like this:

Tom is 5
Ted is 4
Tim is 2

How can i do this? I am new to coding, please do not punish me so much.

+4
source share
2 answers

You can try something like this:

List<Entry<String, Integer>> l = new ArrayList<>(map.entrySet());

Collections.sort(l, new Comparator<Entry<?, Integer>>() {
    @Override
    public int compare(Entry<?, Integer> a, Entry<?, Integer> b) {
        return b.getValue().compareTo(a.getValue());  // reverse order
    }
});

for (int i = 0; i < 10; i++) {
    Entry<String, Integer> e = l.get(i);
    System.out.println(e.getKey() + " is " + e.getValue());
}

Reference:

+10
source

You can use TreeMap and pass Comparatorin a constructor that saves your records in the right order, and then just iterates over yours entrySet.

0
source

All Articles