Home > Enterprise >  How to add a values to arraylist using stream lambda expression
How to add a values to arraylist using stream lambda expression

Time:05-26

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 the car will not be added. I'd like to perform the check via Java stream. I'm using Java 11.

CodePudding user response:

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

CodePudding user response:

You can use findAny(). Refer here.

Stream findAny() returns an Optional (a container object which may or may not contain a non-null value) describing some element of the stream, or an empty Optional if the stream is empty. The behavior of Stream 'findAny()' operation is explicitly non-deterministic, it is free to select any element in the stream. Multiple invocations on the same source may not return the same result.

Use Optional class to check for null pointer exceptions.

Optional<Car> result =  carsInStore.stream().filter(c -> c.getPlateNumber().equals(plateNumber)).findAny();
    if(!result.isPresent()){
      // your logic 
    }

CodePudding user response:

I think I understand your question. You want to replace the for each loop in the addCarToStore method with a streaming API implementation:

Optional<Car> existingCar = carsInStore
    .stream()
    .filter(c -> c.getPlateNumber().equals(plateNumber))
    .findAny();

if (existingCar.isEmpty()) {
    carsInStore.add(new Car(type, model, color, maxSpeed, year, plateNumber));
}

CodePudding user response:

To produce a boolean result if a car with the given property already exists, you need to use anyMatch() operation, which expects a predicate - a function representing a boolean condition.

Opposed to findFirst() and findAny() which are useful when you need to obtain an object as a result, anyMatch() it returns boolean value and there's no need to interpret the optional result.

public boolean addCarToStore(String type, String model, String color,
                             int maxSpeed, int year, String plateNumber) {
    
    boolean alreadyExist = carsInStore.stream()
        .anyMatch(car -> car.getPlateNumber().equals(plateNumber));
    
    if (!alreadyExist) {                
        carsInStore.add(new Car(type, model, color, maxSpeed,
                                year, plateNumber));
    }
    
    return alreadyExist;
}

The method that you've provided will not work as expected. The loop terminate on the first step of iteration without checking all element, i.e. it can potentially return an incorrect result, and you will and up with duplicates in the list.

Double equals sign should be used only if you want to check whether two references point to the same object, otherwise use method equelst() to determine the equality of objects.

  • Related