![](/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.