在列表中查找最旧的,return 最旧的列表

Find oldest in the list and return the list with oldest

这是我的资料:

package victor;

import java.security.PrivateKey;
import java.util.PrimitiveIterator;

public class Car {
    private String mark;
    private String model;
    private int year;
    private String color;
    public Type type;

    public Car(String mark, String model, int year, String color, Type type) {
        this.mark = mark;
        this.model = model;
        this.year = year;
        this.color = color;
        this.type = type;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Car{" +
                "mark='" + mark + '\'' +
                ", model='" + model + '\'' +
                ", year=" + year +
                ", color='" + color + '\'' +
                ", type=" + type +
                '}';
    }
}

现在我必须 return 我列表中最老的那个。这是我的代码:

package victor;

import java.util.ArrayList;
import java.util.List;
    
public class Main {

    public static void main(String[] args) {
        //Create 4 cars (mark,model, production yrs, colour, sedan/coupe/combi/cabrio)

        Car car1 = new Car("BMW", "M5", 2020, "Black", Type.SEDAN);
        Car car2 = new Car("Audi", "SQ8", 2021, "Red", Type.COUPE);
        Car car3 = new Car("Fiat", "Abarth", 2019, "Blue", Type.COUPE);
        Car carTest = new Car("Fiat", "Abarth", 2019, "Blue", Type.COUPE);
        Car car4 = new Car("Ferrari", "Pista", 2020, "Pink", Type.CABRIO);

        List<Car> carList = List.of(car1, car2, car3, car4, carTest);
        List<Car> oldCars = getOldCar(carList);
        System.out.println("This is the oldest car/s: " + oldCars);
    }

    public static List<Car> getOldCar(List<Car> carList) {
        List<Car> oldestCars = new ArrayList<>();
        Car oldCar = carList.get(0); //M5
        for (int i = 0; i < carList.size(); i++) {
            // if i put in the if statment <=  it seems i get  also the  BMW  
            if (carList.get(i).getYear() <= oldCar.getYear()) {
                oldCar = carList.get(i);
                oldestCars.add(carList.get(i));
            }
        }
        return oldestCars;
    }
}

我试图只获得 2 辆最旧的汽车,但显然我也获得了索引 0 中的第一辆汽车,我不知道如何只获得 2019 年的 2 辆菲亚特汽车。

这是我的代码的输出:

This is the oldest car/s: [Car{mark='BMW', model='M5', year=2020, color='Black', type=SEDAN},Car{mark='Fiat', model='Abarth', year=2019, color='Blue', type=COUPE},Car{mark='Fiat', model='Abarth', year=2019, color='Blue', type=COUPE}]

在遍历汽车列表时,存在三种情况下下一辆车的年份与迄今为止最旧汽车的当前年份的关系。根据这三种情况,您可以决定是否要将汽车添加到当前最旧汽车的列表中,或者是否需要创建一个新列表。决定是这样的:

  1. 下一辆车的年份 > 当前最旧的车年份 - 不要做任何事情,这辆车太年轻了...
  2. 下一辆车的年份 == 当前最旧的汽车年份 - 将汽车添加到最旧的汽车列表
  3. 下一辆汽车的年份 < 当前最旧汽车的年份 - 创建一个新的最旧汽车列表,从当前汽车开始。

getOldCar() 方法的代码可能如下所示:

public static List<Car> getOldCar(List<Car> carList) {
    List<Car> oldestCars = new ArrayList<>();
    // always start with the first car in the list
    oldestCars.add(carList.get(0));

    // start at i=1, as the first car is already in the list
    for (int i = 1; i < carList.size(); i++) {
        Car currentCar = carList.get(i);
        int yearLimit = oldestCars.get(0).getYear();
        int currentCarYear = currentCar.getYear();
        if (currentCarYear > yearLimit) {
            // younger, not relevant
        } else if (currentCarYear == yearLimit) {
            // it fits in the current year, add it
            oldestCars.add(currentCar);
        } else {
            // it is older than every other car before, start with a new list
            oldestCars = new ArrayList<>();
            oldestCars.add(currentCar);
        }
    }
    return oldestCars;
}

如果您使用的是 java 8 或更高版本:

在你的主函数中:

将你的 carlist 存储在 ArrayList 中,以便 compareTo 可以使用:

然后拳头对您的列表进行排序,然后 get(0) 最旧,get(size() - 1) 最新车。

public class Main
{
  public static void main (String[]args)
  {
    Car car1 = new Car ("BMW", "M5", 2020, "Black");
    Car car2 = new Car ("Audi", "SQ8", 2021, "Red");
    Car car3 = new Car ("Fiat", "Abarth", 2019, "Blue");
    Car carTest = new Car ("Fiat", "Abarth", 2019, "Blue");
    Car car4 = new Car ("Ferarri", "Pista", 2020, "Pink");

      ArrayList < Car > carList = new ArrayList <> ();
      carList.add (car1);
      carList.add (car2);
      carList.add (car3);
      carList.add (car4);
      carList.add (carTest);

      Collections.sort (carList,
            (a, b)->Integer.compare (a.getYear (), b.getYear ()));

      ArrayList < Car > oldCars =
      findUsingEnhancedForLoop (carList.get (0).getYear (), carList);

      System.out.println ("This is the oldest car/s: " + oldCars.toString ());
  }

  public static ArrayList < Car > findUsingEnhancedForLoop (int year,
                                List < Car > cars)
  {

    ArrayList < Car > oldestCar = new ArrayList <> ();
    for (Car car:cars)
      {
    if (car.getYear () == year)
      {
        oldestCar.add (car);
      }
      }
    return oldestCar;
  }

}

现有代码中,当检测到yonger的车时,现有的older cars列表应该cleared/recreated累加最小年份相关的车:

public static List<Car> getOldCar1(List<Car> carList) {
    List<Car> oldestCars = new ArrayList<>();
    int minYear = 3000;
    for (Car car : carList) {
        if (car.getYear() <= minYear) {
            if (car.getYear() < minYear) {
                minYear = car.getYear();
                oldestCars.clear();
            }
            oldestCars.add(car);
        }
    }
    return oldestCars;
}

使用 Stream API 的类似解决方案可以使用 Collectors.groupingBy 按年份对汽车进行分组,并使用 Collectors.minBy 通过最小键获取值:

public static List<Car> getOldCar(List<Car> carList) {
    return carList.stream()
        .collect(Collectors.groupingBy(Car::getYear)) // Map<Integer, List<Car>>
        .entrySet().stream()
        .collect(Collectors.minBy(Map.Entry::getKey)) // Optional<Map.Entry>
        .map(Map.Entry::getValue) // List<Car>
        .orElse(Collections.emptyList());
}

Online demo 输出:

This is the oldest car/s: [Car{mark='Fiat', model='Abarth', year=2019, color='Blue', type=COUPE}, Car{mark='Fiat', model='Abarth', year=2019, color='Blue', type=COUPE}]

您可以尝试使用高级 for 循环“针对汽车列表中的每辆汽车”

int oldestCarsYear = 0;
Car oldestCar;
for(Car car : carList){
  if(car.getYear() <= oldestCarsYear || oldestCarsYear == 0){
    oldestCarsYear = car.getYear();
    oldestCar = car;
  }
}
oldestCars.add(oldestCar);