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

我有两个对象数组.如果对象符合某个条件,我想用第二个数组中的更新对象更新一个数组.例如,我有这个:

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 -> ...)

*/

我知道我可以做一个简单的for循环来做到这一点.我想知道是否可以使用流来执行此操作.我无法弄清楚在过滤器或之后放入什么.

解决方法:

您可以在此处使用的一个巧妙技巧是创建索引流并使用它们来评估相应的元素:

IntStream.range(0, original.length)

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

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

标签:java,java-8,java-stream

来源: https://codeday.me/bug/20191008/1873512.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值