Thursday, 15 July 2010

java - Sort Map by Top Scores -



java - Sort Map by Top Scores -

i have map stores players name , there score on update , things fine.

public static map<string, integer> map = new hashmap<string, integer>();

after first round of game finishes want remove lowest scores map. instance, there 8 players in map 4 of whom have score of 10 , other 4 have score of 0 how split map in half based on top scorers , remove bottom 4? maintain in mind 8 players not defined, number

i found this post might help. 1 cannot sort hashmap because there no definitive order it. if want sort through linkedhashmap though, how it. (a linkedhashmap has definitive iterative order)

public linkedhashmap sorthashmapbyvalues(hashmap passedmap) { list mapkeys = new arraylist(passedmap.keyset()); list mapvalues = new arraylist(passedmap.values()); collections.sort(mapvalues); collections.sort(mapkeys); linkedhashmap sortedmap = new linkedhashmap(); iterator valueit = mapvalues.iterator(); while (valueit.hasnext()) { object val = valueit.next(); iterator keyit = mapkeys.iterator(); while (keyit.hasnext()) { object key = keyit.next(); string comp1 = passedmap.get(key).tostring(); string comp2 = val.tostring(); if (comp1.equals(comp2)){ passedmap.remove(key); mapkeys.remove(key); sortedmap.put((string)key, (double)val); break; } } } homecoming sortedmap; }

if want remove lowest value on other hand, uncertainty easiest thing sort them.

public static entry<string, integer> removelowest(linkedhashmap<string, integer> map){ entry<string, integer> lowest = null; for(entry<string,integer> e: map){ if(lowest==null || e.getvalue().compareto(lowest.getvalue()) < 0){ lowest = e; } } homecoming lowest; }

ps: don't forget take reply if works you.

update: if want remove half of map. sort first this.

public static linkedhashmap<string, integer> gettophalf(linkedhashmap<string, integer> map){ linkedhashmap<string, integer> sorted = sorthashmapbyvalues(map); linkedhashmap<string, integer> out = new linkedhashmap<string, integer>(); iterator<entry<string,integer>> = sorted.entryset().iterator(); for(int = 0; i<map.size()/2; i++){ entry<string, integer> e = it.next(); out.put(e.getkey(), e.getvalue()); } homecoming out; }

java

No comments:

Post a Comment