-1

I have following method:

private Optional<Car> findCarByID(String id, CarResponse carResponse) {
return carResponse.getCars().stream()
.filter(car -> car.getID().equalsIgnoreCase(id))
.findFirst();

But carResponse can sometimes be null and I want to check this before trying to get the cars and stream them (null pointer exception is raised). I made the check with “if else” like this:

private Optional<Car> findCarByID(String id, CarResponse carResponse) {
if (carResponse!= null) {
return carResponse.getCars().stream()
.filter(car -> car.getID().equalsIgnoreCase(id))
.findFirst();
}
return Optional.empty();
}

Is there any way to include the check carResponse!= null in the beginning of lambda expression and not using “if else”?

Andronicus
  • 25,419
  • 17
  • 47
  • 88

1 Answers1

1

It's correct, adding another optionals into the code can make it less readable. Although ternary operator can save you a couple of keystrokes.

return carResponse == null ? Optional.empty() : carResponse.getCars().stream()
         .filter(car -> car.getID().equalsIgnoreCase(id))
         .findFirst();
Andronicus
  • 25,419
  • 17
  • 47
  • 88