如何按属性对对象的数组列表进行排序?

比方说你有一个Arraylist的HockeyPlayer对象。


如果它们都具有int GoalScored变量,则如何排序?您如何按GoalScored对它们进行排序?


UYOU
浏览 435回答 3
3回答

汪汪一只猫

您可以使用Collections.sort自定义Comparator<HockeyPlayer>。&nbsp; &nbsp; class HockeyPlayer {&nbsp; &nbsp; &nbsp; &nbsp; public final int goalsScored;&nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; };&nbsp; &nbsp; List<HockeyPlayer> players = // ...&nbsp; &nbsp; Collections.sort(players, new Comparator<HockeyPlayer>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override public int compare(HockeyPlayer p1, HockeyPlayer p2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return p1.goalsScored - p2.goalsScored; // Ascending&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });比较部分也可以这样写:players.sort(Comparator.comparingInt(HockeyPLayer::goalsScored));或者,您可以制作HockeyPlayer implementsComparable<HockeyPlayer>。这定义了所有HockeyPlayer对象的自然顺序。使用a Comparator更灵活,因为不同的实现可以按名称,年龄等进行排序。也可以看看Java:实现Comparable和之间有什么区别Comparator?为了完整起见,我应该提醒您注意,return o1.f - o2.f由于可能存在溢出,必须非常谨慎地使用“按减法比较”快捷方式(请阅读:有效的Java 2nd Edition:项目12:考虑实现Comparable)。大概曲棍球不是一项运动,运动员可以得分而导致进球=)

HUX布斯

Java 8只需一行:Collections.sort(players, (p1, p2) -> p1.getGoalsScored() - p2.getGoalsScored());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java