Page 1 of 1
Ordering a hash map
3 Replies - 872 Views - Last Post: 14 December 2009 - 12:22 PM
Posted 14 December 2009 - 04:42 AM
HashMap played = new HashMap();
HashMap goalDifference = new HashMap();
HashMap gameStats = new HashMap();
for(int i = 0; i < matches.size(); i++)
Match match = matches.get(i);
played = getPlayed(match, played, "home");
played = getPlayed(match, played, "away");
goalDifference = getGoalDifference(match, goalDifference, "home");
goalDifference = getGoalDifference(match, goalDifference, "away");
gameStats = getGamesStats(match, gameStats, "home");
gameStats = getGamesStats(match, gameStats, "away");
Object teams = played.keySet().toArray();
Object sorted = gameStats.keySet().toArray();
Replies To: Hash Map
Re: Hash Map
Posted 14 December 2009 - 06:57 AM
In terms of your problem, I would fill in an array with the values of the Map (iterate through it using an Iterator and Set) then use Arrays.sort(). Maps do not maintain order by either the keys or the values, so my solution is probably the easiest way to go.
Re: Hash Map
Posted 14 December 2009 - 07:13 AM
What do you use as keys for the played map? Because you do sort them, but (a) I don't think it's sorting on what you want, (b ) you don't use the sorted array afterwards.
Why do you have 3 different maps?
Why use hashmaps at all? As macosxnerd mentioned, hashmaps are not sorted: you could use either a list, and sort it passing a proper Comparator, or a treemap that sorts the keys in ascending order (but obviously you have to make sure the sorting will be the one you want, i.e. make sure the key is the object you want to sort,, and that it provides the right Comparable implementation).
Give a shout if that's not clear.
This post has been edited by EdwinNameless: 14 December 2009 - 07:14 AM