繁体   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