我有以下程序

 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

先感谢您。

最佳答案

Comparator.comparing()结构旨在用于具有多个字段的对象,因此您可以提取所需的字段用作键。
此方法接受用于提取可比较排序键的函数作为参数。

但是,对于对List 进行排序,则不需要这样做。
由于只有您的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 上这是不必要的,并且最终会重复代码。

如果不清楚,那么这里是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));


然后我们可以像这样对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());

09-13 12:10