[英]Java streams set each attribute of object List with another List
I currently have a list of objects like我目前有一个对象列表,例如
List<Foo> fooList = new ArrayList<>();
Where Foo is: Foo 在哪里:
public class Foo {
public Bar bar;
// getters and setters
}
Now with another List<Bar> barList
I wanted to set each Bar
element to each inner Foo.Bar
element of fooList
using Java streams.现在有了另一个
List<Bar> barList
,我想使用 Java 流将每个Bar
元素设置为fooList
的每个内部Foo.Bar
元素。
I tried to do that using map
function with setBar
but I cannot call a "set" inside map
.我尝试使用
map
function 和setBar
来做到这一点,但我不能在map
中调用“集合”。
You can do it like this.你可以这样做。 It returns a new List of altered
Foo
objects.它返回一个更改后的
Foo
对象的新列表。 The original is changed too.原来的也改了。 I could have used peek to invoke the change but using
peek
in that fashion is considered poor practice.我本可以使用 peek 来调用更改,但以这种方式使用
peek
被认为是不好的做法。
IntStream.range(0, fooList.size()).mapToObj(i -> {
fooList.get(i).setBar(barList.get(i));
return fooList.get(i);})
.collect(Collectors.toList());
I would not use streams for this but a simple for loop.我不会为此使用流,而是使用简单的 for 循环。 For example,
例如,
for (int i = 0; i < fooList.size(); i++) {
fooList.get(i).setBar(barList.get(i));
}
or with an enhanced forloop and local index.或使用增强的 forloop 和本地索引。
int i = 0;
for (Foo f : fooList) {
f.setBar(barList.get(i++));
}
These solutions presume there is a one-to-one ordered mapping of fooList
elements to barList
elements.这些解决方案假定存在
fooList
元素到barList
元素的一对一有序映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.