Saturday, November 5, 2022

[FIXED] How to check whether an object exists a List using Streams

Issue

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 exist 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.


Solution

If you want to rewrite your method using stream, as suggested in the comments, you could check with a stream if a Car with the given plate number already exists within the List; if it does not, then you could add it to carsInStore.

Also, to check whether two String are equal you need to use the equals method. The == operator checks the content of the confronted variables, in case of references their content corresponds to the memory address of the object they point, not the actual value they represent.

private ArrayList<Car> carsInStore;

public boolean addCarToStore(String type, String model, String color, int maxSpeed, int year, String 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;
}


Answered By - Dan
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.