0

I'm looking for a way to hold scores for players for a highscore.

A typical input :

map.put(p1, 9);
map.put(p2, 7);
map.put(p3, 9);

Now I need a way of ordering the map so to be able to see the order of players based on their scores. However, I've tried just sorting based on the value of the map but then I lose cases where two or more players have the same score.

Is a map even the best way to do this or should I try a different data type? All I need is a way to order players based on their scores.

3
  • 1
    Any reason why the score itself is not "part of" the player? Commented Nov 29, 2014 at 17:39
  • @fge it could be reasonable if a single player could have a score in more than one game. Commented Nov 29, 2014 at 17:46
  • Then why not a Map<Integer, List<Player>> for each game? Commented Nov 29, 2014 at 17:48

2 Answers 2

5

I would keep the score for the player within the Player object itself. Then you can just create a list of the players, and order it with a Comparator<Player> implementation that orders by scores - either deliberately making it "highest score first" or using Collections.reverseOrder to reverse the sort order of a "lower score first" comparator.

Sign up to request clarification or add additional context in comments.

1 Comment

Makes much more sense than my answer.
0

A map might be a good way to store the scores; it depends on what else you need to use it for in your program. For example, it would be good if you need to store a separate score for more than one type of game, while using some of the same player objects.

Whether or not storing scores in a map is the best solution for you, you can still use the scores in the map to sort a list of players. Create an implementation of Comparator that compares two players by comparing the scores present in the map. (Integer.compare() might be helpful for this.) Then, create a new list of all the players you want to sort. Finally, use Collections.sort() to sort this list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.