java - Data-structure sorted by value -


i trying store score large of players. need map sorted based on value, because of amount of players it's inefficient sort each time retrieve it. ability find players rank in map. similar score datatype in redis. like:

    scoremap<string, integer> scores = new scoremap<string, integer>();      scores.put("bill", 2);     scores.put("tom", 6);     scores.put("jim", 3);     scores.put("jake", 3);       system.out.println("rank = " + scores.getrank("bill"));      system.out.println();     system.out.println("all:");     (entry<string, integer> entry : scores.entryset()) {         system.out.println(entry.getkey() + " => " + entry.getvalue());     }      system.out.println();     system.out.println("rank range:");     (entry<string, integer> entry : scores.entryrankrange(0, 2)) {         system.out.println(entry.getkey() + " => " + entry.getvalue());     }      system.out.println();     system.out.println("score range:");     (entry<string, integer> entry : scores.entryscorerange(2, 3)) {         system.out.println(entry.getkey() + " => " + entry.getvalue());     } 

this return

    rank = 3      all:     tom => 6     jake => 3     jim => 3     bill => 2      rank range:     tom => 6     jake => 3     jim => 3      score range:     jake => 3     jim => 3     bill => 2 

i know kinda specific , have make custom data-structure. point in right direction appreciated. :)

simplest way use set (namely, treeset) , encapsulate player information (including score) specific class:

public class competitiveplayer implements comparable<competitiveplayer>{      private string name;     private int score;          public competitiveplayer(string name, int score) {         this.name = name;         this.score = score;     }      public string getname() {         return name;     }      public int getscore() {         return score;     }      public void incrementscore() {         score++;     }      @override     public int compareto(competitiveplayer o) {         return score - o.score;     } } 

treeset assumes entires stored in implement comparable interface determining natural ordering of elements.

edit:

if need modify scores of players, map<string, integer>-based solution better fit, because there's no get in java's set. this thread discusses map-based approach in great detail.

one simplictic solution (as suggested in mentioned thread) one-liner, using guava library:

map<string, integer> sortedscores = immutablesortedmap.copyof(scores,     ordering.natural().onresultof(functions.formap(scores))); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -