![](/img/trans.png)
[英]Using Java Streams to group together a List of objects by an attribute and reduce them to a new list of object with the average of another attribute
[英]Java streams set each attribute of object List with another List
我目前有一个对象列表,例如
List<Foo> fooList = new ArrayList<>();
Foo 在哪里:
public class Foo {
public Bar bar;
// getters and setters
}
现在有了另一个List<Bar> barList
,我想使用 Java 流将每个Bar
元素设置为fooList
的每个内部Foo.Bar
元素。
我尝试使用map
function 和setBar
来做到这一点,但我不能在map
中调用“集合”。
你可以这样做。 它返回一个更改后的Foo
对象的新列表。 原来的也改了。 我本可以使用 peek 来调用更改,但以这种方式使用peek
被认为是不好的做法。
IntStream.range(0, fooList.size()).mapToObj(i -> {
fooList.get(i).setBar(barList.get(i));
return fooList.get(i);})
.collect(Collectors.toList());
我不会为此使用流,而是使用简单的 for 循环。 例如,
for (int i = 0; i < fooList.size(); i++) {
fooList.get(i).setBar(barList.get(i));
}
或使用增强的 forloop 和本地索引。
int i = 0;
for (Foo f : fooList) {
f.setBar(barList.get(i++));
}
这些解决方案假定存在fooList
元素到barList
元素的一对一有序映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.