0

I have an unsorted array of players that came through a JSON response:

"participants": [{
    "participant": {
        "rank": 3,
        "name": "I Tied for third",
    }
}, {
    "participant": {
        "rank": 1,
        "name": "I got first",
    }
}, {
    "participant": {
        "rank": 3,
        "name": "Also tied for third",
    }
}, {
    "participant": {
        "rank": 2,
        "name": "I got second",
    }
}]

I would like to sort this somehow so that I can eventually print out both the player's name, and their rank... but in order.

I thought about possibly putting the results of the array into a TreeMap, but then I realised that TreeMaps require unique array keys and that wouldn't work:

Map<Integer, String> players = new TreeMap<>();

for (int i = 0; i < participants.length(); i++) {
    JSONObject object = participants.getJSONObject(i);
    JSONObject participant = object.getJSONObject("participant");

    players.put(participant.getInt("rank"), participant.getString("name"));
}

So is there another way to get this done?

Jason Axelrod
  • 7,155
  • 10
  • 50
  • 78
  • [Android how to sort JSONArray of JSONObjects](http://stackoverflow.com/questions/12901742/android-how-to-sort-jsonarray-of-jsonobjects) this may be helpful to you . – Developer Feb 02 '16 at 07:31

1 Answers1

0

With @VivekMishra helping, I was able to get it working:

ArrayList<PlayerObject> players = new ArrayList<>();

for (int i = 0; i < participants.length(); i++) {
    JSONObject object = participants.getJSONObject(i);
    JSONObject participant = object.getJSONObject("participant");

    players.add(new PlayerObject(participant.getInt("rank"), participant.getString("name")));
}
Collections.sort(players);

With:

class PlayerObject implements Comparable<PlayerObject> {
    private int rank;
    private String name;

    public PlayerObject(int r, String n) {
        setRank(r);
        setName(n);
    }

    public int compareTo(PlayerObject other) { return rank - other.rank; }

    public int getRank() { return rank; }
    public void setRank(int text) { rank = text; }

    public String getName() { return name; }
    public void setName(String text) { name = text; }
}
Jason Axelrod
  • 7,155
  • 10
  • 50
  • 78