-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”?

2

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.