2017-03-08 50 views
2

我有两个对象数组。如果对象符合特定条件,我想用第二个数组中的更新对象更新一个数组。例如,我有这样的:Java 8 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或之后放置什么。你可以在这里使用

+0

如果你想要一些帮助,您必须是具体的标准。 – NiVeR

+2

基于流的代码不会像直接用于此操作的传统代码那样清晰或高效。 _Don't bother._ –

+1

你说得对。它似乎比传统的for循环方法运行得慢。不过,我认为Mureinik发布的答案非常可读。 –

回答

4

一个绝妙的技巧是创建索引的数据流,并用它们来评估相应的元素:

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

谢谢,这个作品很棒。 –

相关问题