Java 8 stream replace object in one array from another

ⅰ亾dé卋堺 提交于 2019-12-30 11:05:21

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/42682019/java-8-stream-replace-object-in-one-array-from-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!