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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With