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]);