使用Java LIST将集合【{宝马1系,1000},{宝马2系,2000},{奥迪2系,2000},{奥迪1系,1000}】排序,先排名称,后排价格
时间: 2023-11-01 14:30:21 浏览: 66
可以通过编写一个自定义的Comparator来实现对集合的排序,以下是Java代码示例:
```
import java.util.*;
public class Car {
private String name;
private int price;
public Car(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
class CarComparator implements Comparator<Car> {
@Override
public int compare(Car car1, Car car2) {
int nameComparison = car1.getName().compareTo(car2.getName());
if (nameComparison != 0) {
return nameComparison;
}
return Integer.compare(car1.getPrice(), car2.getPrice());
}
}
public class Main {
public static void main(String[] args) {
List<Car> cars = new ArrayList<>();
cars.add(new Car("宝马1系", 1000));
cars.add(new Car("宝马2系", 2000));
cars.add(new Car("奥迪2系", 2000));
cars.add(new Car("奥迪1系", 1000));
Collections.sort(cars, new CarComparator());
for (Car car : cars) {
System.out.println(car.getName() + " " + car.getPrice());
}
}
}
```
输出结果为:
```
宝马1系 1000
宝马2系 2000
奥迪1系 1000
奥迪2系 2000
```
阅读全文