简体   繁体   中英

How to make Pairs using Stream for two lists

I have two lists:

List<Flight> flightsToCity = findFlightToCity(airport);
List<Flight> flightsFromCity = findFlightFromCity(airport);

Elements of lists are flights. I must connect every flights from list flightsToCity, with every element of second list and this must be pairs. I must do this with stream and result it must be List<Pair<Flight, Flight>> For example:

flightsToCity:

London -> Warsow,
Berlin -> Warsow

flightFromCity:

Warsow -> Barcelona,
Warsow -> Zakopane

Result:

London -> Warsow, Warsow -> Barcelona
London -> Warsow, Warsow -> Zakopane
Berlin -> Warsow, Warsow -> Barcelona
Berlin -> Warsow, Warsow -> Zakopane

Assuming that the lists have the same size and the elements are in the right order you could use an IntStream to solve your problem.

        List<Pair<Flight, Flight>> flightsOfAirport = IntStream
            .range(0, flightsFromCity.size())
            .mapToObj(index -> Pair.of(flightsToCity.get(index), flightsFromCity.get(index)))
            .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM