Home > Blockchain >  Convert stream into a for loop java
Convert stream into a for loop java

Time:04-25

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();
}

CodePudding user response:

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);
}

CodePudding user response:

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();
}
  • Related