我有这样的类结构:
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());
}
有没有简化这个的方法?