讓我們想象一下以下對象:合併2只列出了一個功能性反應方式
class People {
public int id;
public String name;
public Date dateOfDeath;
}
我有2名人名單。
在第一個中,People對象的ID和NAME已正確設置。在第二個中,People對象的ID和DATEOFDEATH正確設置。
我需要結合2個列表纔能有一個完整的People對象(名稱和死亡日期)的單個列表。
在一個完整的程序辦法,這可能是與雙來完成的循環是這樣的:
for (People fullPeople : firstList) {
for (People peopleWithDateOfDeath : secondList) {
if (peopleWithDateOfDeath.id == fullPeople.id) {
fullPeople.dateOfDeath = peopleWithDateOfDeath.dateOfDeath;
break;
}
}
}
secondList = null;
// first list is good :)
我怎麼能在一個功能性的方式實現這一點?我正在使用Rx-Java,但任何使用Java 8 Streams的例子都很容易轉換。
感謝這個乾淨的例子。按照程序的方式,可以通過刪除任何已經匹配的人來優化內部循環,以避免必須更深入地搜索日期列表。在我的情況下,這可以幫助很多,因爲我知道這兩個列表都將在ID上排序。任何方式在功能上做同樣的優化? – pdegand59
@ pdegand59 Misha的答案可以爲你做到這一點:你可以調用'deaths.remove(p.id)'而不是'deaths.get(p.id)'。 – Tunaki