简体   繁体   中英

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:

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.

I tried to do that using map function with setBar but I cannot call a "set" inside map .

You can do it like this. It returns a new List of altered Foo objects. The original is changed too. I could have used peek to invoke the change but using peek in that fashion is considered poor practice.

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 example,

for (int i = 0; i < fooList.size(); i++) {
    fooList.get(i).setBar(barList.get(i));
}

or with an enhanced forloop and local index.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM