本文介绍了使用Java8 Streams从另外两个列表创建对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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以更简洁的方式处理前一个问题?

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

推荐答案

Stream绑定到给定的Iterable/Collection,因此您不能真正并行"迭代两个collection.

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());

这篇关于使用Java8 Streams从另外两个列表创建对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 04:43