vendredi 12 juillet 2019

Converting for loops and if into java streams

I want to convert some for loops and if's into streams as I know they are much better and more readable. Im begginer in it, so I need your help.

 for (ViewFlightRouteDTO flightRoute : routes) {
            ViewFlightDTO flightData = flightRoute.getFlightData();

            if ( airportIataCode.equals(flightData.getArrivalIata().getCode()) ) {
                associatedFlights.get(ViewFlightRouteAirportType.ARRIVAL).add(flightData);
            }
            if ( airportIataCode.equals(flightData.getDepartureIata().getCode()) ) {
                associatedFlights.get(ViewFlightRouteAirportType.DEPARTURE).add(flightData);
            }

            for (ViewFlightRouteAirportType associatedAirportType : etopsAndNonEtopsAssociatedAirportTypes) {
                for (ViewFlightAirportDTO airport : flightRoute.getAirportsForType(associatedAirportType)) {
                    if ( airportIataCode.equals(airport.getIataCode()) ) {
                        addValueIfNotPresent(associatedFlights, associatedAirportType, flightData);
                    }
                }
            }
        }

AssociatedFlights is Map<ViewFlightRouteAirportType, Set<ViewFlightDTO>> associatedFlights = new EnumMap<>(ViewFlightRouteAirportType.class);

I have tried like this, but do not know how to add after filter flightData into associatedFlights and then how to work with nested for loop.

 associatedFlights =  routes.stream()
               .map(ViewFlightRouteDTO::getFlightData)
               .filter(flightData -> airportIataCode.equals(flightData.getArrivalIata().getCode()))
               //need to add flightData here
               .filter(flightData -> airportIataCode.equals(flightData.getDepartureIata().getCode()))
               //need to add flightData here
               .collect(toMap());

Aucun commentaire:

Enregistrer un commentaire