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?

1

1 Answer 1

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; }
}
Sign up to request clarification or add additional context in comments.

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.