我有以下程序
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)
到比较器
先谢谢您
答案 0 :(得分:1)
Comparator.comparing()结构旨在用于具有多个字段的对象,因此您可以提取所需的字段用作键。 此方法接受用于提取可比排序键的功能作为参数。
但是,对列表
由于只有您的String值,没有其他可作为键的模糊字段。
如果要在(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 ]
但是正如您所看到的,在List
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));
然后我们可以像这样对List
// 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());
答案 1 :(得分:0)
您正在相互比较字符串,以便对列表进行排序。
如果您使用a+b
进行排序,则意味着比较的结果将始终为您提供相同的结果
使用以下代码
numbers.sort((a, b) -> a.compareTo(b));
答案 2 :(得分:0)
以下是一些 当您有复杂的对象并且要根据其属性进行排序时,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/