Reputation: 75
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.
Upvotes: 4
Views: 102
Reputation: 1975
You can use a TreeMap and pass a Comparator
in the constructor which keeps your entries in the desired order, then just iterate over your entrySet
.
Upvotes: 0
Reputation: 129537
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:
Upvotes: 10