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