运行 ❯
获取您自己的
Java 服务器
×
更改方向
更改主题,暗/亮
转到 Spaces
import java.util.ArrayList; import java.util.Collections; // Define a Car class class Car { public String brand; public String model; public int year; public Car(String b, String m, int y) { brand = b; model = m; year = y; } } public class Main { public static void main(String[] args) { // Create a list of cars ArrayList<Car> myCars = new ArrayList<Car>(); myCars.add(new Car("BMW", "X5", 1999)); myCars.add(new Car("Honda", "Accord", 2006)); myCars.add(new Car("Ford", "Mustang", 1970)); // Use a lambda expression to sort the cars Collections.sort(myCars, (obj1, obj2) -> { Car a = (Car) obj1; Car b = (Car) obj2; if (a.year < b.year) return -1; if (a.year > b.year) return 1; return 0; }); // Display the cars for (Car c : myCars) { System.out.println(c.brand + " " + c.model + " " + c.year); } } }
福特野马 1970
宝马 X5 1999
本田雅阁 2006