3 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
如果調(diào)用getCsByIds成本很高,那么您最初的想法很適合自己執(zhí)行。它可以進(jìn)一步縮短為:
public Map<A, List<C>> convert(Collection<A> as) {
List<Long> cIds = as.stream()
.flatMap(a -> a.getBs().stream())
.map(B::getIdOfC)
.collect(Collectors.toList());
Map<Long, C> csMap = getCsByIds(cIds).stream()
.collect(Collectors.toMap(C::getId, Function.identity()));
return as.stream()
.collect(Collectors.toMap(Function.identity(),
a -> a.getBs().stream().map(b -> csMap.get(b.getIdOfC()))
.collect(Collectors.toList()), (a, b) -> b));
}
您可以在其中相應(yīng)地選擇合并功能(a,b) -> b。

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
也許只是直接迭代 As ?(手頭沒(méi)有編譯器,所以片段可能沒(méi)有編譯就緒)
public Map<A, List<C>> convert(Collection<A> as) {
Map<A, List<C>> result = new HashMap<>();
for(A a: as){
List<Long> cIds = a.getBs().stream()
.map(B::getIdOfC)
.collect(Collectors.toList());
result.put(a, getCsByIds(cIds));
}
return result;
}

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
像這樣的東西不會(huì)起作用嗎?我沒(méi)有編譯器,所以我無(wú)法真正測(cè)試它
public Map<A, List<C>> convert(Collection<A> as) {
return as.stream()
.collect(Collectors.toMap(Function::identity,
a -> a.getBs().stream()
.map(B::getIdOfC)
.flatMap(id -> getCsByIds(asList(id))
.values()
.stream())
.collect(Collectors.toList())
)
);
}
添加回答
舉報(bào)