在Java中按姓氏和名字对对象的ArrayList进行排序


问题内容

我有一个基于运动的不同类型球员的arrayList。我需要按姓氏对arrayList中的播放器列表进行排序以开始。如果2个玩家的姓氏相同,则需要按名字对这2个玩家进行排序。示例:格式姓氏姓氏Williams
Robert Phillips Warren Doe John Phillips Mark

输出应为Doe John Phillips Mark Phillips Warren Williams Robert

我现在所拥有的仅按我的代码中的第一个或最后一个atm进行排序。

   public static void sortPlayers(ArrayList playerList) {
    for (int i = 0; i < playerList.size(); i++) {
        for (int j = 0; j < playerList.size(); j++) {
            Collections.sort(playerList, new Comparator() {

                public int compare(Object o1, Object o2) {
                    PlayerStats p1 = (PlayerStats) o1;
                    PlayerStats p2 = (PlayerStats) o2;
                    return p1.getPlayerLastName().compareToIgnoreCase(p2.getPlayerLastName());
                }
            });
        }

    }
}

问题答案:

将比较器更改为:

            public int compare(Object o1, Object o2) {
                PlayerStats p1 = (PlayerStats) o1;
                PlayerStats p2 = (PlayerStats) o2;
                int res =  p1.getPlayerLastName().compareToIgnoreCase(p2.getPlayerLastName());
                if (res != 0)
                    return res;
                return p1.getPlayerFirstName().compareToIgnoreCase(p2.getPlayerFirstName())
            }