Parthanaux
Parthanaux

Reputation: 135

Sorting a map in android

I have a following method where i read data from Android shared preferences, and I am wondering if there is a way to sort the map by value when the entry values are <String,capture<?>>. I am writing to shared preferences with putString("name",int score).

public String readScores(){
        String returnString = "";
        int iterator = 1;
        SharedPreferences shared = getSharedPreferences("highscores", MODE_PRIVATE);
        Map<String, ?> values = shared.getAll();
        for (Map.Entry<String, ?> entry : values.entrySet())
        {
            returnString += "<tr><td>" + String.valueOf(iterator) + "</td><td>" + entry.getKey() + "</td><td>" + String.valueOf(entry.getValue()) + "</td></tr>";
            iterator++;
        }
        return returnString;
    }

Upvotes: 1

Views: 183

Answers (1)

kmera
kmera

Reputation: 1745

You could create a list out of your entryset and sort that list using Collections.sort.

//test data
Map<String, String> values = new HashMap<>();   
values.put("foo", "c");
values.put("bar", "b");
values.put("baz", "a");

for (Map.Entry<String, String> entry : values.entrySet()) {
    System.out.println(entry);
}

System.out.println("-----------sort by value-----------");

List<Map.Entry<String, String>> entries = new ArrayList(values.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, String>>() {

    public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { 
        return o1.getValue().compareTo(o2.getValue());
    }

});

for (Map.Entry<String, String> entry : entries) {
    System.out.println(entry);
}

Output:

baz=a
foo=c
bar=b
-----------sort-----------
baz=a
bar=b
foo=c

Try it here.

Upvotes: 1

Related Questions