Using Java8 Streams to create a list of objects from another two lists

前端 未结 3 1623
执笔经年
执笔经年 2020-12-14 19:13

I have the following Java6 and Java8 code:

List lst1 = // a list of ObjectType1 objects
List lst2 = // a list of Object         


        
3条回答
  •  星月不相逢
    2020-12-14 19:48

    A Stream is tied to a given iterable/Collection so you can't really "iterate" two collections in parallel.

    One workaround would be to create a stream of indexes but then it does not necessarily improve over the for loop. The stream version could look like:

    List lst3 = IntStream.range(0, lst1.size())
             .mapToObj(i -> new ObjectType3(lst1.get(i).getAVal(), lst2.get(i).getAnotherVal()))
             .collect(toList());
    

提交回复
热议问题