使用 Java8 Streams 从另外两个列表创建对象列表

2022-01-22 00:00:00 lambda java-8 java java-stream

我有以下 Java6 和 Java8 代码:

I have the following Java6 and Java8 code:

List<ObjectType1> lst1 = // a list of ObjectType1 objects
List<ObjectType2> lst2 = // a list of ObjectType1 objects, same size of lst1

List<ObjectType3> lst3 = new ArrayLis<ObjectType3>(lst1.size());
for(int i=0; i < lst1.size(); i++){
  lst3.add(new ObjectType3(lst1.get(i).getAVal(), lst2.get(i).getAnotherVal()));
}

Java8 中有什么方法可以使用 Lambda 以更简洁的方式处理前面的 for 吗?

Is there any way in Java8 to handle the previous for in a more concise way using Lambda?

推荐答案

Stream 绑定到给定的可迭代/集合,因此您不能真正并行迭代"两个集合.

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

一种解决方法是创建一个索引流,但它不一定会改进 for 循环.流版本可能如下所示:

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<ObjectType3> lst3 = IntStream.range(0, lst1.size())
         .mapToObj(i -> new ObjectType3(lst1.get(i).getAVal(), lst2.get(i).getAnotherVal()))
         .collect(toList());

相关文章