0

I kind of need this stream reverse engineered into a for loop. How would it look?

public Optional<Flight> getFlightByFlightNumber(String flightNumber) {
    return flights.stream()
            .filter(flt -> flt.getFlightNumber().equals(flightNumber))
            .findFirst();
}
1
  • 1
    just check what it does. That should already show you how to convert it. Commented Apr 25, 2022 at 5:55

2 Answers 2

2

It will something like this:

public Optional<Flight> getFlightByFlightNumber(String flightNumber) {
    Flight flightByFlightNumber = null;
    for (Flight flight : flights) {
        //You might want to add a null check here before calling equals method, to avoid NullPointerException
        if (flight.getFlightNumber().equals(flightNumber)) {
            flightByFlightNumber = flight;
            // breaking the loop as we found first match
            break;
        }
    }
    return Optional.ofNullable(flightByFlightNumber);
}
Sign up to request clarification or add additional context in comments.

2 Comments

yet there is one big difference between the original code and this
@Stultuske Thanks for the hint, added the break statement
0

Here is one way.

  • just iterate over the list until the flight is found and return directly in an Optional.
  • otherwise, return an empty optional when the loop finishes.
public Optional<Flight> getFlightByFlightNumber(String flightNumber) {
    for (Flight flight : flights) {
        if (flight.getFlightNumber.equals(flightNumber)) {
            return Optional.of(flight);
        }
    }
    return Optional.empty();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.