2017-03-08 88 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

謝謝,這個作品很棒。 –

相關問題