我有这样的类结构:
public class A {
private List<B> bs;
...//getters
}
public class C {
private Long id;
...//getters
}
public class B {
private Long idOfC;
...//more stuff
}
B::getIdOfC 匹配 C::getId
在更好的设计中,B 将只包含对 C 的引用,而不是它的 id(我无法更改它),所以这就是为什么现在我需要创建一个映射,所以我的方法签名看起来像这样
public Map<A, List<C>> convert(Collection<A> collection)
在这个转换方法里面,有一个
List<C> getCsByIds(List<Long> id)
稍后用于将其与 B.idOfC 进行匹配,但应该只调用一次此方法,因为它非常昂贵。
所以如果我这样走:
List<B> bs = Arrays.asList(new B(10L), new B(11L)); //10L and 11L are the values of idOfC
List<A> as = Arrays.asList(bs);
//And assuming getCsByIds returns Arrays.asList(new C(10L), new C(11L), new C(12L));
然后
Map<A, List<C>> map = convert(as);
map.values().get(0)
返回类似Arrays.asList(new C(10L), new C(11L))
在我看来,这样做的方法非常庞大:
public Map<A, List<C>> convert(Collection<A> as) {
List<Long> cIds = as.stream()
.flatMap(a -> a.getBs().stream())
.map(B::getCId)
.collect(Collectors.toList());
//single call to gsCsByIds
Map<Long, C> csMap = getCsByIds(cIds)
.stream()
.collect(Collectors.toMap(C::getId, Function.identity()));
//a whole new map is created by iterating over the list called "as"
Map<A, List<C>> csByAs = new HashMap<>();
if (!csMap.isEmpty()) {
for (A a : as) {
Set<C> cs = getCsFromMap(csMap, a.getBs());
if (!cs.isEmpty()) {
csByAs.put(a, new ArrayList<>(cs));
}
}
}
return csByAs;
}
private Set<B> getCsFromMap(Map<Long, C> cMap, List<B> bs) {
return bs.stream()
.map(b -> cMap.get(b.getIdOfc()))
.collect(Collectors.toSet());
}
有没有办法让这个更简单???
最佳答案
如果对 getCsByIds
的调用开销很大,那么您最初的想法很适合自行执行。它可以进一步缩短为:
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));
}
您可以在其中相应地选择合并函数 (a,b) -> b
。
关于java8 简化映射转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55092214/