简体   繁体   English

如何使用 Stream 对两个列表进行配对

[英]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.我必须将列表 FlightsToCity 中的每个航班与第二个列表的每个元素连接起来,这必须是成对的。 I must do this with stream and result it must be List<Pair<Flight, Flight>> For example:我必须用流来做这件事,结果它必须是List<Pair<Flight, Flight>>例如:

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.假设列表具有相同的大小并且元素的顺序正确,您可以使用IntStream来解决您的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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