Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get top 10 Keys in decreasing order of their values for the Map<String, Integer>

Tags:

java

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

And then I could broadcast it like:

Tom is 5
Ted is 4
Tim is 2

How may I do this? I'm beginner in coding, please don't punish me so hard.

like image 205
Luis Avatar asked Dec 25 '22 20:12

Luis


1 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:

  • Map.entrySet()
  • Collections.sort()
  • Comparator
like image 99
arshajii Avatar answered Dec 28 '22 10:12

arshajii