简体   繁体   English

Java 流设置 object 列表的每个属性与另一个列表

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

相关问题 使用Java Streams按属性将对象列表组合在一起,并将它们减少为具有另一个属性平均值的新对象列表 - 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:使用流转换列表 <Object> 到另一个列表 <anotherObject> - Java : use Streams to convert List<Object> to another List<anotherObject> 使用 Java 8 Streams 从另一个创建对象列表 - Create list of object from another using Java 8 Streams Java 8流,将对象列表转换为Map <String, Set<String> &gt; - Java 8 streams, convert List of object to Map<String, Set<String>> 合并与 List 中每个唯一对象相关的数据,并使用 Streams 将它们转换为另一种类型的 List - Merge the data relating to each unique Object in a List and transform them into a List of another Type using Streams 使用Java流将Java List转换为另一个 - Converting Java List to another using java streams Java 8 - 如何在另一个列表中的 object 的列表中设置 object? - Java 8 - How to set an object in a list from an object in another list? 如何在java 8中迭代对象数组列表并设置为另一个对象列表? - How to iterate List of object array and set to another object list in java 8? 使用流将 Java 列表转换为映射,其中映射中的每个值共享相同的属性 - Convert Java list into map where each value in map shares same attribute, using streams Java8 流:创建一个新的 object 并将其添加到列表中,同时迭代另一个列表 - Java8 streams : Creating a new object and adding it to list while iterating over another list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM