Using Java8 Streams to create a list of objects from another two lists(使用 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 以更简洁的方式处理前面的 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());
这篇关于使用 Java8 Streams 从另外两个列表创建对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Java8 Streams 从另外两个列表创建对象列表
基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
