Sorting HashMaps?

Discussion in 'Plugin Development' started by Stigosaurus, Mar 31, 2013.

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

    Stigosaurus

    How can I sort a HashMap? I am saving player scores in a HashMap<String, Integer> and want to know how I can sort it to retrieve the highest scores out of all the entries. With lists, you can do Collections.sort(<list>), but there is nothing with a HashMap. Thanks!
     
  2. Offline

    molenzwiebel

    Can't you get the values by map.values() and then Collections.sort(list)?
     
  3. Offline

    stirante

    HashMap don't have anything like hashMap.get(0). I mean you can't get first element of HashMap becous ethere is no first element.
     
  4. Offline

    Stigosaurus

    stirante So how can I get top scores then?
     
  5. Offline

    the_merciless

    Try something like this:

    Code:
        static HashMap <String, Integer> unordered = new HashMap <String, Integer>();
        public static HashMap <String, Integer> ordered = new HashMap <String, Integer>();
     
    public static HashMap<String, Integer> highscores(){
            String playername;
            int highestvalue = 0;
            for (int i = 0; unordered.size() > 0; i++){
                for (Entry<String, Integer> e : unordered.entrySet()){
                    if (e.getValue() > highestvalue){
                        highestvalue = e.getValue();
                        playername = e.getKey();
                        ordered.put(playername, highestvalue);
                        unordered.remove(playername);
                    }
                }
            }
            return ordered;
        }
    Then you can use:

    Code:
    [S]String first = highscores.get(1);[/S]
    [S]String second = highscores.get(2);[/S]
    [S]String third = highscores.get(3);[/S]
     
    [S]Bukkit.broadcastMessage("Top 3: 1st - " + first + " 2nd - " + second + " 3rd - " + third);[/S] 
    Hold on cant do that.
     
  6. Offline

    Cybermaxke

    Why not using comparators to sort the map?
     
  7. Offline

    stirante

    This is untested and I'm not sure if it will work at all.

    Code:
    class ValueComparator implements Comparator<String> {
     
        Map<String,Double> base;
        public ValueComparator(Map<String,Double> base){
            this.base = base;
        }
     
        // Note: this comparator imposes orderings that are inconsistent with equals.   
        public int compare(String a,String b){
            if(base.get(a)>= base.get(b)){
                return-1;
            }else{
                return1;
            }// returning 0 would merge keys
        }}
    Code:
            ValueComparator comp =  new ValueComparator(yourMap);
            TreeMap<String,Double> sorted_map =new TreeMap<String,Double>(comp);
            System.out.println("unsorted map: "+yourMap);
     
            sorted_map.putAll(yourMap);
     
            System.out.println("results: "+sorted_map);
    
     
  8. Offline

    the_merciless

    Ignore my last post heres how i would do it (Untested):

    Code:
    public class High_to_low {
     
        static HashMap <String, Integer> unordered = new HashMap <String, Integer>();
        public static HashMap <String, Integer> ordered = new HashMap <String, Integer>();
     
        public static void sortScores(){
            String playername;
            int highestvalue = 0;
            for (int i = 0; i < unordered.size(); i++){
                for (Entry<String, Integer> e : unordered.entrySet()){
                    if (e.getValue() > highestvalue){
                        highestvalue = e.getValue();
                        playername = e.getKey();
                        ordered.put(playername, highestvalue);
                        unordered.remove(playername);
                    }
                }
            }
        }
     
        public void displayTopThree(){
            sortScores()
            String pname;
            int score;
            for (int i = 0; 1 < 3; i++){
                for (Entry<String, Integer> e : ordered.entrySet()){
                    pname = e.getKey();
                    score = e.getValue();
                    bukkit.broadcastMessage("" + i + ". " + pname + ": " + score);
                }
            }
        }
     
    }
     
  9. Offline

    Stigosaurus

    the_merciless I tested that and it will print out the top player and their score three times instead of the top three...

    stirante what will sorted_map print out?

    stirante omg thanks! It works in just a general java application, now let me test it in a plugin!

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 31, 2016
  10. Offline

    LucasEmanuel

    the_merciless
    A hashmap does not save the order if its data. Thereby you cannot sort a standard hashmap and expect it to keep the order.
     
  11. Offline

    raGan.

    Can be easily avoided. Do string comparison when values are equal.
    Code:
    public int compare(String a,String b){
        // sorting from high to low
        if(base.get(a) > base.get(b)){
            return -1;
        }
        if(base.get(a) < base.get(b)){
            return 1;
        }
        // entries with the same values are sorted alphabetically
        return a.comparaTo(b);
    }
     
    stirante likes this.
  12. Offline

    Stigosaurus

    stirante how would I print the top three values out?
     
  13. Offline

    stirante

    sorted_map.navigableKeySet();

    Then you can from iterator get these values becouse iterator also iterates in right order.
     
Thread Status:
Not open for further replies.

Share This Page