假设我有以下 2 个对象:
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());
我很确定我需要在过滤器之后做一些事情,但是当我需要对象本身时,过滤器当然只返回一个 boolean 值。该怎么办??
最佳答案
我不太明白你的策略。特别是,根本没有任何指令可以修改 DetailObject 的 masterId,并且您正在创建新的 DetailObject 实例,尽管我看不出有任何理由这样做。
此外,您正在将字符串与 ==
进行比较。
为什么不循环遍历详细信息,对于每个详细信息,查找具有相同属性的主数据库,如果找到,则更新详细信息的 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;
}
}
}
关于java - 如何流式传输和映射一对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42940100/