问题描述
我有一个基于体育的不同类型球员的阵列列表。我需要按照姓氏对arrayList中的玩家列表进行排序才能开始。如果2个玩家具有相同的姓氏,则需要按照名字对这2个玩家进行排序。
示例:格式姓氏名字
Williams Robert
Phillips Warren
Doe John
Phillips Mark
I have an arrayList of different types of players based on sports. I need to sort the list of players in the arrayList by last name to start. If 2 players have the same last name it needs to then sort those 2 players by the first name.example: Format Lastname firstnameWilliams RobertPhillips WarrenDoe JohnPhillips Mark
输出应该是
Doe John
Phillips Mark
Phillips Warren
Williams Robert
Output should be Doe JohnPhillips MarkPhillips WarrenWilliams Robert
我现在只有第一个或者最后我在我的代码中使用最后一个atm。
What i have now only sorts by either the first or last i have it by last atm in my code.
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())
}
这篇关于按Java中的姓氏和名字对对象的ArrayList进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!