如何按属性对对象的数组列表进行排序?
2022-09-01 03:29:05
假设您有一个对象。Arraylist
HockeyPlayer
如果他们都有一个可变的int进球得分,你怎么能排序呢?您如何按进球得分对它们进行排序?
假设您有一个对象。Arraylist
HockeyPlayer
如果他们都有一个可变的int进球得分,你怎么能排序呢?您如何按进球得分对它们进行排序?
您可以将 Collections.sort
与自定义 Comparator<HockeyPlayer>
。
class HockeyPlayer {
public final int goalsScored;
// ...
};
List<HockeyPlayer> players = // ...
Collections.sort(players, new Comparator<HockeyPlayer>() {
@Override public int compare(HockeyPlayer p1, HockeyPlayer p2) {
return p1.goalsScored - p2.goalsScored; // Ascending
}
});
比较部分也可以这样写:
players.sort(Comparator.comparingInt(HockeyPLayer::goalsScored));
或者,您可以制作Compeable<HockeyPlayer>
。这定义了所有对象的自然排序。使用 更灵活,因为不同的实现可以按名称、年龄等排序。HockeyPlayer implements
HockeyPlayer
Comparator
为了完整起见,我应该提醒一下,由于可能存在溢出,必须极其谨慎地使用逐减比较快捷方式(阅读:有效的Java第2版:第12项:考虑实现可比较
)。据推测,曲棍球不是一项球员可以进球的运动,其进球数量会导致问题=)return o1.f - o2.f
作为@user6158055 suggets,它是一个带有 的衬里,如下所示:Java 8
Collections.sort(
hockeyPlayerList,
(player1, player2) -> player1.getGoalsScored()
- player2.getGoalsScored());
完整的示例来描述相同的内容:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<HockeyPlayer> hockeyPlayerList = new ArrayList<>();
hockeyPlayerList.add(new HockeyPlayer("A", 3));
hockeyPlayerList.add(new HockeyPlayer("D", 10));
hockeyPlayerList.add(new HockeyPlayer("B", 2));
System.out.println("Before Sort based on goalsScored\n");
hockeyPlayerList.forEach(System.out::println);
System.out.println("\nAfter Sort based on goalsScored\n");
Collections.sort(
hockeyPlayerList,
(player1, player2) -> player1.getGoalsScored()
- player2.getGoalsScored());
hockeyPlayerList.forEach(System.out::println);
}
static class HockeyPlayer {
private String name;
private int goalsScored;
public HockeyPlayer(final String name, final int goalsScored) {
this.name = name;
this.goalsScored = goalsScored;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGoalsScored() {
return goalsScored;
}
public void setGoalsScored(int goalsScored) {
this.goalsScored = goalsScored;
}
@Override
public String toString() {
return "HockeyPlayer [name=" + name + ", goalsScored="
+ goalsScored + "]";
}
}
}
输出:
Before Sort based on goalsScored
HockeyPlayer [name=A, goalsScored=3]
HockeyPlayer [name=D, goalsScored=10]
HockeyPlayer [name=B, goalsScored=2]
After Sort based on goalsScored
HockeyPlayer [name=B, goalsScored=2]
HockeyPlayer [name=A, goalsScored=3]
HockeyPlayer [name=D, goalsScored=10]