0

Supposing that I have a hashmap with the following structure:

HashMap<int, String> players = new HashMap<int, String>();
players.put(2, 'player1');
players.put(1, 'player2');
players.put(4, 'player3');
players.put(3, 'player4');
players.put(5, 'player5');

How can I output it like this with a for loop?

5, player5
4, player3
3, player4
2, player1
1, player2
zearthur99
  • 101
  • 7

1 Answers1

4

You can create a TreeMap<k,v> with the existing HashMap

   Map<int, String> newMap = new TreeMap(Collections.reverseOrder());
    newMap.putAll(players);

So that your existing players map is unchanged. And you get the newMap sorted in descending order

Santhosh
  • 8,181
  • 4
  • 29
  • 56