Solved Sorting a HashMap by Integer values in descending order (Strictly Java Issue)

Discussion in 'Plugin Development' started by AoH_Ruthless, Jun 16, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    AoH_Ruthless

    I am trying to sort arenas (more than one) by integer values in a hashmap in descending order. Using a comparator, I can get a sorted list of arenas in ascending order according to integer value but not in descending order.

    My code:

    Code:java
    1. final Map<Arena, Integer> timesPlayed = new HashMap<Arena, Integer>();
    2. // This is where I input arenas and their integer values, code not shown because irrelevant
    3. // Sort the map
    4. List<Arena> list = new ArrayList<Arena>(timesPlayed.keySet());
    5. Collections.sort(list, new Comparator<Arena>() {
    6. @Override
    7. public int compare(Arena a1, Arena a2) {
    8. Integer timesPlayed1 = timesPlayed.get(a1);
    9. Integer timesPlayed2 = timesPlayed.get(a2);
    10. return timesPlayed1.compareTo(timesPlayed2); // I tried also comparing to -timesPlayed2 but this doesn't sort properly
    11. }
    12. });
    13.  
    14. // All code after this is irrelevant to issue
    15. }
     
  2. Offline

    Rocoty

    Reverse the compareTo call by calling it on the second value and passing the first. Or you could negate the returned value.
     
  3. Offline

    AoH_Ruthless

    Rocoty likes this.
  4. Offline

    Rocoty

    AoH_Ruthless Yeah that will do the same as my first suggestion behind the scenes, if one is to believe GrepCode.
     
    AoH_Ruthless likes this.
Thread Status:
Not open for further replies.

Share This Page