【发布时间】:2016-02-02 07:28:01
【问题描述】:
我有一个通过 JSON 响应来的未排序的玩家数组:
"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",
}
}]
我想以某种方式对其进行排序,以便最终打印出玩家的姓名和他们的排名……但要按顺序。
我考虑过可能将数组的结果放入 TreeMap,但后来我意识到 TreeMap 需要唯一的数组键,这行不通:
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"));
}
那么还有其他方法可以完成这项工作吗?
【问题讨论】: