[英]How to stream and map a one-to-many relationship?
說我有以下兩個對象:
public class MasterObject {
Long masterId;
Long detailId;
String attribute1;
//...
}
public class DetailObject {
Long detailId;
String attribute2;
//..
}
我有一個包含10個主對象的超集列表,以及一個包含2個詳細對象的子集列表。 最后,在驗證了attribute1 == attribute2之后,我需要一組新的10個詳細對象(從主數據庫復制信息),並帶有適當的詳細ID。 對於每個細節對象,我需要創建一個新的主對象。 到目前為止,這是我想出的,但這是不正確的。 請注意我的評論欄:
List<DetailObject> updatedDetails = masterObjects.stream()
.filter(master -> {
return detail.stream()
.anyMatch(it -> master.getAttribute1() == detail.getAttribute2());
})
.map(master -> {
DetailObject detailObject = new DetailObject();
// Here is where I thought I could set the master Id in the detail object,
// but I no longer have access to the original detail stream
return detailObject;
})
.collect(Collectors.toList());
我很確定我需要在過濾器之后做一些事情,但是當我需要對象本身時,過濾器當然只會返回一個布爾值。 該怎么辦??
我不太了解您的策略。 特別是,根本沒有任何指令可以修改DetailObject的masterId,盡管我看不出有任何理由來修改DetailObject的masterId。
此外,您正在將String與==
進行比較。
您為什么不單單瀏覽詳細信息,對於每個詳細信息,查找具有相同屬性的母版,如果找到,則更新詳細信息的masterId?
details.forEach(
d -> masters.stream()
.filter(m -> m.getAttribute1().equals(d.getAttribute2()))
.findAny()
.ifPresent(m -> d.setMasterId(m.masterId)));
這是O(m * n),但是對於m和n分別為2和10來說,這並不重要。
您也可以使用循環:
for (Master m : masters) {
for (Detail d : details) {
if (m.getAttribute1().equals(d.getAttribute2())) {
d.setMasterId(m.getMasterId());
break;
}
}
}
我和我的同事找到了解決我問題的方法。 看起來像這樣:
List<DetailObject> newDetails = details.stream()
.map(detail -> {
return masters.stream()
.filter(master -> filterLoans(detail, master))
.map(master -> createDetail(detail, master))
.collect(Collectors.toList());
})
.flatMap(List::stream)
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.