如何通过属性对对象的数组列表进行sorting?

让我们假设你有一个HockeyPlayer对象的Arraylist

你怎么能sorting,如果他们都有一个variablesint goalsscored 。 你怎么能通过目标进行sorting呢?

您可以使用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)); 

另外,你可以让HockeyPlayer implements Comparable<HockeyPlayer> 。 这定义所有HockeyPlayer对象自然顺序。 使用Comparator器更灵活,因为不同的实现可以按名称,年龄等进行sorting

也可以看看

  • Java:实现ComparableComparator什么区别?

为了完整return o1.f - o2.f ,我应该注意,由于可能的溢出,必须谨慎使用return o1.f - o2.f by-subtraction快捷方式(请参阅Effective Java第2版:第12项:考虑实现Comparable )。 推测曲棍球不是一种运动员,他们可以在导致问题的量上得分的目标=)

也可以看看

  • Java整数:什么是更快的比较或减法?

写一个自定义比较器来完成这项工作。

使用Bean比较器之类的通用比较器 。

Java 8的一行:

 Collections.sort(players, (p1, p2) -> p1.getGoalsScored() - p2.getGoalsScored()); 

作为@ user6158055build议,它是Java 8的一个class轮,如下所示:

 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] 

Java有这样的一套sort()方法。 有关详细信息,请参阅Collections.sort(和Comparable)。