我有两个对象数组。如果对象符合特定条件,我想用第二个数组中更新的对象来更新一个数组。例如,我有这个:
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/