- 一:对整数进行排序
-
List<Integer> numbers =Arrays.asList(6,2,1,4,9);
-
System.out.println(numbers);//[6, 2, 1, 4, 9]
-
numbers.sort(Comparator.naturalOrder());
-
System.out.println(numbers);//[1, 2, 4, 6, 9]
- 二、按字符串字段对列表进行排序
-
List<Movie> movies =Arrays.asList(
-
newMovie("Lord of the rings"),
-
newMovie("Back to the future"),
-
newMovie("Carlito's way"),
-
newMovie("Pulp fiction"));
-
movies.sort(Comparator.comparing(Movie::getTitle));
-
movies.forEach(System.out::println);
- 提取的类型是String,而String实现了
Comparable
接口,所以list能正确排序。 -
三、按double字段排序列表
-
List<Movie> movies =Arrays.asList(
-
newMovie("Lord of the rings",8.8),
-
newMovie("Back to the future",8.5),
-
newMovie("Carlito's way",7.9),
-
newMovie("Pulp fiction",8.9));
-
movies.sort(Comparator.comparingDouble(Movie::getRating)
-
.reversed());
-
movies.forEach(System.out::println);
- 我们使用反转函数(
reversed
)来反转默认从低到高的自然排序,Comparator.comparingDouble()
底层使用Double.compare()
实现。如果需要比较int
或long
,可以分别使用comparisonInt()
和comparisonLong()
。 - 四、使用自定义比较器多列表进行排序
-
List<Movie> movies =Arrays.asList(
-
newMovie("Lord of the rings",8.8,true),
-
newMovie("Back to the future",8.5,false),
-
newMovie("Carlito's way",7.9,true),
-
newMovie("Pulp fiction",8.9,false));
-
movies.sort(newComparator<Movie>(){
-
@Override
-
publicint compare(Movie m1,Movie m2){
-
if(m1.getStarred()== m2.getStarred()){
-
return0;
-
}
-
return m1.getStarred()?-1:1;
-
}
-
});
- 我们可以使用
lambda
表达式而不是匿名类(Anonymousclass
),如下所示: -
movies.forEach(System.out::println);
-
movies.sort((m1, m2)->{
-
if(m1.getStarred()== m2.getStarred()){
-
return0;
-
}
-
return m1.getStarred()?-1:1;
-
});
- 也可以使用
Comparator.comparing()
: -
movies.sort(Comparator.comparing(Movie::getStarred,(star1, star2)->{
-
if(star1 == star2){
-
return0;
-
}
-
return star1 ?-1:1;
-
}));
-
-
-
-
-
List<Integer> numbers =Arrays.asList(6,2,1,4,9);
-
System.out.println(numbers);//[6, 2, 1, 4, 9]
-
numbers.sort(Comparator.naturalOrder());
-
System.out.println(numbers);//[1, 2, 4, 6, 9]
原文链接:https://dzone.com/articles/java-8-comparator-how-to-sort-a-list
作者: Mario Pio Gioiosa
译者:Steephan