Java 8 – how do I copy attribute values from one list to another?

I have two lists, for example:

List<Foo> list1 = Lists.newArrayList(new Foo(...),...);
List<Bar> list2 = Lists.newArrayList(new Bar(...),...);

There is an attribute in the bar, fooid Suppose LIST1 size()== list2. size(). I want to set the fooids of the bar instance in order

I try the following code:

int index = 0;
list2.forEach(b -> b.fooId = list1.get(index++).getId());

But the compilation failed

Does Java 8 have any convenient way to handle it?

Solution

You cannot modify an index variable from a lambda expression

You can iterate the index using intstream (although this is not much better than a simple for loop):

IntStream.range(0,list1.size())
         .forEach(i -> list2.get(i).setFooId(list1.get(i).getId()));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>