问题描述
假设您有一个 HockeyPlayer
对象的 Arraylist
.
Lets say you have an Arraylist
of HockeyPlayer
objects.
如果他们都有一个变量int目标得分,你怎么排序.您如何按目标得分对它们进行排序?
How could you sort that if they all have a variable int goalsScored. How could you sort them by goalsScored?
推荐答案
您可以使用 Collections.sort
带有自定义 Comparator
.
You can use Collections.sort
with a custom 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
}
});
比较部分也可以这样写:
The comparision part can also be written this way :
players.sort(Comparator.comparingInt(HockeyPLayer::goalsScored));
或者,您可以使 HockeyPlayer 实现
可比的
.这定义了所有 HockeyPlayer
对象的 自然顺序.使用 Comparator
更加灵活,因为不同的实现可以按名称、年龄等排序.
Alternatively, you can make HockeyPlayer implements
Comparable<HockeyPlayer>
. This defines the natural ordering for all HockeyPlayer
objects. Using a Comparator
is more flexible in that different implementations can order by name, age, etc.
为了完整起见,我应该注意 return o1.f - o2.f
比较减法快捷方式必须非常谨慎,因为可能会溢出(阅读:Effective Java第二版:第 12 项:考虑实现 Comparable
).大概曲棍球不是一项运动,其中球员可以进球的数量会导致问题=)
For completeness, I should caution that the return o1.f - o2.f
comparison-by-subtraction shortcut must be used with extreme caution due to possible overflows (read: Effective Java 2nd Edition: Item 12: Consider implementing Comparable
). Presumably hockey isn't a sport where a player can score goals in the amount that would cause problems =)
这篇关于如何按属性对对象数组列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!