Mariano Molina Mariano Molina - 7 months ago 126
Android Question

Organize HashMap by value (Firebase Database Snapshot)

New at Java programming and couldn't find an answer for this.

I created a Firebase Database for a small game I built and managed to get the scores to be stored correctly. Now I want to build the leaderboard with the top ten scores. The database itself is indexed by top scores, and I get the top 10 scores with:

mDatabase.child(gameName).child("Score").limitToFirst(10).addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
HashMap<String,Long> topScores = (HashMap<String, Long>) dataSnapshot.getValue();

The problem with that is that (from what I can see) what I receive is a HashMap which I store in topScores. Again, from what I understand so far, HashMaps are unorganized, so when you print it, it looks something like this:

{DummyData1=0, try=0, dummy2=5, lalala=10, Name1=0, try2=0, lala=11, try3=0, la=3, dummy=1}

So, no discernible order.

Finally, the question is how would you recommend I go about ordering the HashMap created in order to store the Key and Value pairs in their corresponding TextView (the top scorer and top score in the first Row of TextViews, and so on).

As a reference, how I plan on showcasing the leaderboard



Sort a Map<Key, Value> by values (Java)

This will return a new map sorted by the value:(java 8 required)

public static <K, V extends Comparable<? super V>> Map<K, V> 
    sortByValue( Map<K, V> map )
    Map<K, V> result = new LinkedHashMap<>();
    Stream<Map.Entry<K, V>> st = map.entrySet().stream();

    st.sorted( Map.Entry.comparingByValue() )
        .forEachOrdered( e -> result.put(e.getKey(), e.getValue()) );

    return result;