簡體   English   中英

Java 流設置 object 列表的每個屬性與另一個列表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM