I have to create a result list by adding objects.
Here is my code.
private ArrayList<Car> carsInStore;
public boolean addCarToStore(String type, String model, String color, int maxSpeed, int year, String plateNumber) {
for (Car car : carsInStore) {
if (car.getPlateNumber() == plateNumber) {
return false;
}
else {
carsInStore.add(new Car(type, model, color, maxSpeed, year, plateNumber));
return true;
}
}
}
I need to check if a car with the given plateNumber
already exists within the ArrayList
, if it exists, then a new car will not be added.
I'd like to perform the check via Java streams.
I'm using Java 11.
If you want to rewrite your method using streams, you could: stream your list, filter by the given plate number, find if there's any element left after filtering, and finally check if any car is present in the Optional
representing the first element found.
Alternatively, you could compact the filter and check steps with the terminal operation anyMatch()
.
Also, notice that in order to check if two strings are equal, you should use the equals()
method, not the operator ==
. This is because ==
checks the content of the variables compared, but since car.getPlateNumber()
and plateNumber
are two references, their content is the memory address of the String
objects they're pointing to, not the String
representations.
To properly compare two strings, you need to use equals()
as the method returns true
if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
private ArrayList<Car> carsInStore;
public boolean addCarToStore(String type, String model, String color, int maxSpeed, int year, String plateNumber) {
// Alternatively
// .filter(c -> Objects.equals(c.getPlateNumber(), plateNumber))
if (carsInStore.stream()
.filter(c -> c.getPlateNumber().equals(plateNumber))
.findFirst()
.isEmpty()) {
return false;
}
carsInStore.add(new Car(type, model, color, maxSpeed, year, plateNumber));
return true;
}
private ArrayList<Car> carsInStore;
public boolean addCarToStore(String type, String model, String color, int maxSpeed, int year, String plateNumber) {
// Alternatively
// .anyMatch(c -> Objects.equals(c.getPlateNumber(), plateNumber))
if (carsInStore.stream()
.anyMatch(c -> c.getPlateNumber().equals(plateNumber))) {
return false;
}
carsInStore.add(new Car(type, model, color, maxSpeed, year, plateNumber));
return true;
}