我有以下程序
List<String> numbers = Arrays.asList("10", "68", "97", "9", "21", "12");
Collections.sort(numbers, (a, b) -> (b + a).compareTo(a + b));嗨
如何重写这段代码?
(b + a).compareTo(a + b)
转到Comparator.comparing
提前谢谢你。
发布于 2019-02-20 07:28:30
Comparator.comparing()结构用于具有多个字段的对象,因此您可以提取要用作键的所需字段。此方法接受用于提取可比较排序键的函数作为参数。
但是,要对列表进行排序,则不需要这样做。
因为只有您的字符串值,而没有其他可以用作键的模糊字段。
如果要在(a+b).compareTo(b+a)上对此列表进行排序
List<String> numbers = Arrays.asList("10", "68", "97", "9", "21", "12");然后,使用标准比较器的代码:
numbers.sort((a, b) -> (a+b).compareTo(b+a));以及使用Compartor.comparing的代码:
numbers.sort(Comparator.comparing((String s) -> s, (a, b) -> (a+b).compareTo(b+a)));两项产出都将:
[ 10, 12, 21, 68, 97, 9 ]但正如您所看到的,在列表中这是不必要的,最终会重复代码。
如果不清楚,那么下面是一个恰当的Comparator.comparing用例
假设我们有这门课
public class Car {
private String name;
private String type;
private int tires;
public Car(String name, String type, int tires) {
this.name = name;
this.type = type;
this.tires= tires;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public int getTires() {
return tires;
}
}还有一张汽车清单
List<Car> carsList = new ArrayList<Car>();
carsList.add(new Car("Audi A3", "Hatchback", 4));
carsList.add(new Car("Tyrerell P34", "Formula One", 6));
carsList.add(new Car("1932 Morgan Aero 2-Seater Sports", "Sports", 3));
carsList.add(new Car("Avtoros Shaman", "All terrain", 8));然后我们就可以像这样排列一个列表
// By the type
carsList.sort(Comparator.comparing(Car::getType));
// By the number of tires
carsList.sort(Comparator.comparingInt(Car::getTires));
// By the number of tires in reverse order
carsList.sort(Comparator.comparingInt(Car::getTires).reversed());
// First by the type and then by the number of tires in reverse order
carsList.sort(Comparator.comparing(Car::getType).thenComparing(Car::getTires).reversed());发布于 2019-02-20 06:55:09
您正在比较字符串彼此,以使您的列表排序。
如果使用a+b进行排序,则意味着比较的结果将始终给出相同的结果。
使用以下代码
numbers.sort((a, b) -> a.compareTo(b));发布于 2019-02-20 07:07:51
下面是一些Comparator.comparing的示例,当您有复杂的对象并且想要根据它的属性进行排序时,这些示例是有用的。在下面,我已经根据字符串的长度对其进行了排序。
List<String> numbers = Arrays.asList("10", "68", "97", "9", "21", "12");
Collections.sort(numbers, Comparator.naturalOrder()); //[10, 12, 21, 68, 9, 97]
Collections.sort(numbers, Comparator.reverseOrder()); //[97, 9, 68, 21, 12, 10]
numbers.sort(Comparator.comparing(String::length)); //[9, 97, 68, 21, 12, 10]
numbers.sort(Comparator.comparing(String::intern)); //[10, 12, 21, 68, 9, 97]
numbers.sort(Comparator.comparing((String num) -> num, (a, b) -> (b+a).compareTo(a+b)));// [9, 97, 68, 21, 12, 10]
List<Movie> movies = Arrays.asList(
new Movie("Lord of the rings"),
new Movie("Back to the future"),
new Movie("Carlito's way"),
new Movie("Pulp fiction"));
movies.sort(Comparator.comparing(Movie::getTitle));参考文献:https://reversecoding.net/java-8-comparator-how-to-sort-a-list/
https://stackoverflow.com/questions/54780263
复制相似问题