Sorting scores

Discussion in 'Plugin Development' started by thepaperboy99, Nov 28, 2013.

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

    thepaperboy99

    Hello Bukkit, I need help finding a way to sort a hashmap that stores a string and a integer to find what player has the highest score. For example:

    map.put("player1",10);
    map.put("player2",22);
    map.put("player3",4);

    What I need it to be:

    1 = player2
    2 = player1
    3 = player3

    How would I be able to sort it to get the player with the highest kills? Thanks!
     
  2. Offline

    pope_on_dope

    Code:
    public static Map<String, Integer> sortByValue(Map<String, Integer> map) {
            List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());
     
            Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
     
                public int compare(Map.Entry<String, Integer> m1, Map.Entry<String, Integer> m2) {
                    return (m2.getValue()).compareTo(m1.getValue());
                }
            });
     
            Map<String, Integer> result = new LinkedHashMap<String, Integer>();
            for (Map.Entry<String, Integer> entry : list) {
                result.put(entry.getKey(), entry.getValue());
            }
            return result;
        }
    will return a new map with all the values sorted.
     
  3. Offline

    thepaperboy99


    Thanks! I will test this when I get home



    The code works and everything, but how would I get the top one? I tried map.get(0), but that didn't work. Any suggestions?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 5, 2016
  4. Offline

    pope_on_dope

    Code:
    String firstname = (String) map.keySet().toArray()[0];
    int firstscore = (int) map.values().toArray()[0]
     
  5. Offline

    thepaperboy99


    Thanks! Works perfectly!
     
Thread Status:
Not open for further replies.

Share This Page