Search code examples
javaobjectarraylistreturn

Iterate through ArrayList of objects, and return the object


I want to iterate through an ArrayList of objects, and then I want to return the object that has a specific attribute.

I tried this:

public Car findCar(String wantedColor){
    for (Car car : carList){
        if (wantedColor.equals(car.getColor())){
            return car;
        }
    }
    // Can't put return statement here because it's dependent of if statement
}

This doesn't work because the return statement is inside the 'if statement'. But I can't put the return statement in the indicated line, because it's dependent of the if statement...

Assume that there is always one car with each color. So there is always exactly one Car I'm looking for, no more and no less.

How can I ensure that there is always one object to be found and that it is returned?


Solution

  • Initialize the Car object to be returned outside the loop.

    Car carWithWantedColor = null;
    for (Car car : carList){
        if (wantedColor.equals(car.getColor())){
            carWithWantedColor =  car;
            break;
        }
    }
    return carWithWantedColor;
    

    But if it contradicts with what you have said, and if a non-existing color is passed, this would return null. These kinds of things should normally be avoided IMO.

    I would prefer to use Optional in this case.

    If you want to terminate with an exception, you do as following

    carList.stream()
           .filter(car -> car.getColor().equals(wantedColor))
           .findFirst()
           .orElseThrow(() -> new RuntimeException("Invalid color"));