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
  • 6
  • 2
    use a Treemap: http://stackoverflow.com/questions/922528/how-to-sort-map-values-by-key-in-java – s_bei Jan 30 '15 at 13:47

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,131
  • 3
  • 28
  • 56