0

I'm new to Java and to this forum and I hope you can help me out; I'm working in Android Studio and I would like to keep and display a Top 5 highScore list in my application.

For everytime someone finish the game I get the score and firstname of the player;

private void saveScore(){
String firstname = mPreferences.getString(PREF_KEY_FIRSTNAME, null);
int score =mPreferences.getInt(PREF_KEY_SCORE, 0);


//add name and score to map and save in shared preferences

Map<String,Integer> highScores=new HashMap<>();
    highScores.put(firstname, score);
    for (String s : highScores.keySet()) {
        prefHighscore.edit().putInt(s, highScores.get(s));
    }
    prefHighscore.edit().apply();

}

I then want to access the map in my ScoreActivity private void getScores() {

    HashMap<String, Integer> map= (HashMap<String, Integer>) 
prefHighscore.getAll();
    for (String s : map.keySet()) {
        Integer value = map.get(s);

}

I hope this code is allright. I now get stuck because I would like to:

1.sort the list and get five highscores. 2.get the name and score for the five and display them

Can you give me some hints?

Eliza
  • 1
  • 1
  • For sorting the list, you can just [bubble sort](https://en.wikipedia.org/wiki/Bubble_sort#Analysis). The basic idea is that you run through all the numbers (with a for loop) and swap the number and the number after it if the number after it is smaller than the number. Repeat that process until the list is sorted. – Pieter Mantel Sep 25 '18 at 17:14
  • You can maybe try this to sort a hashmap by values https://stackoverflow.com/questions/8119366/sorting-hashmap-by-values/13913206 – Macmist Sep 25 '18 at 17:25
  • Thank you for your answers. Is there anyway to sort out five keys and values from the hashMap even though it contains more than five? Or do I have to make sure that my map only holds 5? – Eliza Sep 29 '18 at 07:06

0 Answers0