1

So, I need to sort a "scores" hashmap. the hashmap layout is HashMap<Player, Integer(which is the score i need to sort>

if you're asking why? its because i need to make a leaderboard.

here is my code:

public static Player[] sortPlayersByElo() {
        Map<String, Object> map = RankingConfig.get().getConfigurationSection("data").getValues(false);
        Map<Player, Integer> eloMap = new HashMap<>(); // Here is the map i need to sort.
        for (String s : map.keySet()) {
            Player player = Bukkit.getPlayer(s);
            eloMap.put(player, RankingConfig.get().getInt("data."+s+".elo"));
        }
        
        Player[] players = new Player[eloMap.size()];

        return players;
    }
Aly Mobarak
  • 356
  • 2
  • 17

1 Answers1

4

You can use Comparator.comparingInt to sort in the correct order. Streams can be used to sort and collect the new Map to a LinkedHashMap to retain the new order.

Map<Player, Integer> result = eloMap.entrySet().stream()
    .sorted(Comparator.comparingInt(Map.Entry::getValue))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
         (a,b)->b, LinkedHashMap::new));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80