gpt4 book ai didi

java - 如何编写 Comparator.comparing

转载 作者:行者123 更新时间:2023-12-02 10:14:25 29 4
gpt4 key购买 nike

我有以下程序

 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());

关于java - 如何编写 Comparator.comparing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54780263/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com