Java 8流将一个数组中的对象替换为另一个数组 [英] Java 8 stream replace object in one array from another

查看:1065
本文介绍了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]);

这篇关于Java 8流将一个数组中的对象替换为另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆