I am filtering out a List<Car>
based on the brand. Since each car is made by one brand, I want to make sure my method getCar()
is called and just a single car is returned. If it returns more than one car, throw an exception.
This is a simplified example, my current implementation is as follows:
I have a list of cars stored in an array list, please assume this list cars
already has car object stored in them.
Also, in my Car
class implementation, I have a method call isCorrectBrand()
which check if the brand matches.
List<Car> cars;
public Car getCar(String brand) {
List<Car> filteredCars = new ArrayList<>();
cars.stream()
.filter(car -> car.isCorrectBrand(brand))
.forEach(filteredCars::add);
if (filteredCars.size() > 1) {
throw new Exception("");
} else {
return filteredCars.get(0);
}
}
My approach is to first loop through the cars
list, store them in a temp list, and if the list is size one, that means everything is fine, otherwise it indicates something wrong with either the brand message or the isCorrectBrand()
implementation.
My questions are:
Is the exception thrown an appropriate one, if not what exception is appropriate for this use?
Is there a better way of writing this?