-3

I got these objects in constructor.

cars.add(new Car(2016, "honda", "civic"));
cars.add(new Car(2017, "Lamborghini", "aventador"));
cars.add(new Car(2000, null, "caravan"));
cars.add(new Car(2010, "dodge", null));

I need to return all the data from it in the following format: hondacivicLamborghiniaventadorcaravandodge

My function is:

public String listAllCars()
{
    String result;
    result = null;

    if(cars == null)
    {
        throw new IllegalArgumentException("c cannot be null");
    }

    for(Car car: cars)
    {

        if(car.getMake() != null || car.getModel() != null) 
        {
            result += car.getMake() + car.getModel();
        }

    }

    return result; 
}

But I end up with nullhondacivicLamborghiniaventadornullcaravandodgenull instead of hondacivicLamborghiniaventadorcaravandodge.

feedthemachine
  • 592
  • 2
  • 11
  • 29

2 Answers2

0

You are checking whether any one of make or model are not null. But, your case requires you to check for both make and model individually and concatenate if present.

for(Car car: cars) {
    if(car.getMake() != null) { result += car.getMake(); }
    if(car.getModel() != null) { result += car.getModel(); }
}
0

You need to append each field if it's not null independently. For compactness you may use Objects.toString. For efficiency, a simple if will do.

If you are ok with using Streams API:

public String listAllCars() {
    if (cars == null) {
        throw new IllegalArgumentException("c cannot be null");
    }

    return cars.stream()
            .map(c -> Objects.toString(c.getMake(), "")
                    + Objects.toString(c.getModel(), ""))
            .reduce("", (a, b) -> a + b);
}

Or, using the imperative style, but with a StringBuilder:

public String listAllCars() {
    if (cars == null) {
        throw new IllegalArgumentException("c cannot be null");
    }

    StringBuilder result = new StringBuilder();

    for (Car car : cars) {
        result.append(Objects.toString(car.getMake(), ""));
        result.append(Objects.toString(car.getModel(), ""));
    }

    return result.toString();
}

Or, without the StringBuilder:

public String listAllCars() {
    if (cars == null) {
        throw new IllegalArgumentException("c cannot be null");
    }

    String result = "";

    for (Car car : cars) {
        result += Objects.toString(car.getMake(), "");
        result += Objects.toString(car.getModel(), "");
    }

    return result;
}
rph
  • 2,104
  • 2
  • 13
  • 24