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

标签 java java-8 java-stream

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

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 循环来执行此操作。我想知道是否可以使用流来做到这一点。我不知道要在 filter 中或之后放入什么。

最佳答案

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

IntStream.range(0, original.length)
         .filter(i -> original[i].getName().equals(updated[i].getName()))
         .forEach(i -> original[i] = updated[i]);

关于Java 8流将一个数组中的对象替换为另一个数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42682019/

相关文章:

Java 在管道中生成自定义流

spring - Java 8 Spring 兼容性

java - 如何在groupby后获取新列表并对一个属性求和

java - 如何为 google pubsub 发布者和订阅者设置超时?

java - 执行操作系统相关命令

Java 8 函数风格编程柯里化(Currying)和函数组合有什么区别

lambda - Intellij 中的 Java Lambda : Expected not null but the lambda body is not value-compatible

java - Stream.parallel() 不是更新了spliterator 的特性吗?

javascript - Nashorn 多线程编程

java - 当 AsyncTask 完成 Activity 时调用 fragment 方法