【问题标题】:How to sort a nested array in Android/Java?如何在 Android/Java 中对嵌套数组进行排序?
【发布时间】: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"));
}

那么还有其他方法可以完成这项工作吗?

【问题讨论】:

标签: java android


【解决方案1】:

在@VivekMishra 的帮助下,我能够让它工作:

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);

与:

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; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2020-02-06
    • 2019-06-04
    • 1970-01-01
    • 2019-09-30
    • 2014-03-10
    相关资源
    最近更新 更多