假设您有Arraylist
个HockeyPlayer
个对象。
如果他们都有变量 int goalsScored ,你如何排序?你怎么能按目标排序呢?
答案 0 :(得分:87)
您可以将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
更灵活,因为不同的实现可以按名称,年龄等排序。
为了完整起见,我应该提醒一下,由于可能出现溢出,必须非常谨慎地使用return o1.f - o2.f
逐个减法比较快捷方式(阅读: Effective Java 2nd Edition:第12项:考虑实施{{ 1}} 的)。据推测,曲棍球并不是一项运动,玩家可以在可能导致问题的数量上进球。=)
答案 1 :(得分:5)
正如@ user6158055所说,它是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]
答案 2 :(得分:3)
编写自定义Comparator来完成工作。
答案 3 :(得分:2)
使用类似Bean Comparator的通用比较器。
答案 4 :(得分:2)
使用Java 8只需一行:
getComputedStyle()
答案 5 :(得分:0)
Java有一组sort()方法用于此类事情。有关详细信息,请参阅Collections.sort(和Comparable)。
答案 6 :(得分:0)
使用Java 8,这很简单
Collections.sort(playList, Comparator.comparingInt(HockeyPLayer::goalsScored))