Fox*_*zer 1 java sorting collections object comparable
假设一个对象有一个 int ID 号字段,但没有实现 Comparable。我想按照我自己的排序标准对这些对象使用 Collections.sort() 。是否有可能做到这一点?
您可以提供一个比较器,例如
List<MyType> list = ...
Collections.sort(list, new Comparator<MyType>() {
public int compare(MyType a, MyType b) {
return Integer.compare(a.getX(), b.getX());
}
});
Run Code Online (Sandbox Code Playgroud)
在 Java 8 中你可以这样做
list = list.stream()
.sort(Comparator.comparingInt(MyType::getX))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
或者
Collections.sort(list, comparingInt(MyType::getX));
Run Code Online (Sandbox Code Playgroud)