Search code examples
javalistcollectionsmin

Find oldest in the list and return the list with oldest


Here is what I have:

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 +
                '}';
    }
}

Now I have to return the oldest in my list. Here is my code:

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;
    }
}

I tried to get only the 2 oldest cars but apparently I get also the first car in as is index 0 and I cannot figure it out how to get only the 2 Fiat cars of 2019.

Here is the output from my code:

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}]


Solution

  • In the existing code, when a yonger car is detected, the existing list of old cars should be cleared/recreated to accumulate the cars related to the minimal year:

    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;
    }
    

    Similar solution using Stream API may group by cars by year using Collectors.groupingBy, and get the values by the minimal key using 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 output:

    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}]