java数组替换,Java 8流将一个数组中的对象替换为另一个数组

I have two arrays of objects. I want to update one array with updated objects from the second array if the object matches a certain criteria. For example, I have this:

public class Foobar

{

private String name;

// Other methods here...

public String getName() { return this.name; }

}

Foobar [] original = new Foobar[8];

// Instantiate them here and set their field values

Foobar [] updated = new Foobar[8];

// Instantiate them here and set their field values

/* Use Java8 stream operation here

* - Check if name is the same in both arrays

* - Replace original Foobar at index with updated Foobar

*

* Arrays.stream(original).filter(a -> ...)

*/

I know I can make a simple for loop to do this. I want to know if it's possible to do this using streams. I can't figure out what to put in filter or after that.

解决方案

One neat trick you can use here is to create a stream of indexes and use them to evaluate the corresponding elements:

IntStream.range(0, original.length)

.filter(i -> original[i].getName().equals(updated[i].getName()))

.forEach(i -> original[i] = updated[i]);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值