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}]
CodePudding user response:
While iterating over the list of cars there are three cases how the year of the next car is in relation to the current year of the oldest cars so far. Based on these three cases you decide if you want to add the car to the list of currently oldest cars or if you need to create a new list. The decision is like this:
- Year of next car > current oldest car year - Don't do anything, the car is too young...
- Year of next car == current oldest car year - Add car to oldest cars list
- Year of next car < current oldest car year - Create a new list of oldest cars, starting with the current car.
The code of the getOldCar()
method might look like this:
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;
}
CodePudding user response:
If you are using java 8
or above:
In your main function:
store your carlist in ArrayList, so that compareTo
can be used:
then Fist sort your list and then get(0)
for oldest and get(size() - 1)
for newest car.
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;
}
}
CodePudding user response:
You could try an advanced for loop "for every car in car list"
int oldestCarsAge = 0;
Car oldestCar;
for(Car car : carList){
if(car.getAge() <= oldestCarsAge){
oldestCarsAge = car.getAge();
oldestCar = car;
}
}
oldestCars.add(oldestCar);
CodePudding user response:
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}]