我试图重构java 8代码以获得更好的可读性,并且还能够调试代码 . 我有一个函数返回Map的CompletionStage,键为String,值为someItem .
return response.thenApplyAsync(
r -> {
Map<String, someItem> result = new HashMap<>();
// The result can be null
if (r != null) {
result = r.getItemList().stream().collect(
Collectors.toMap(
x -> x.getFirstBlock().getSomevalue(), Function.identity(),
// check and warn for duplicates
(p1, p2) -> {
LOGGER.warn(String.format("duplicate some value found: %s",
p1.getFirstBlock().getSomevalue()));
return p1;
})
);
}
return result;
}
);
我重构了代码:
try {
someItem1 respVal=response.toCompletableFuture().get();
List<someItem> itmLst=respVal.getItemList();
Map<String, someItem> result=new HashMap<String, someItem>();
for(someItem itm:itmLst){
if(result.containsKey(itm.getFirstBlock().getSomevalue())){
LOGGER.warn(String.format("duplicate some value found: %s",itm.getFirstBlock().getSomevalue()));
}else{
result.put(itm.getFirstBlock().getSomevalue(),itm);
}
}
return CompletableFuture.completedFuture(result);
} catch (InterruptedException|ExecutionException e) {
e.printStackTrace();
}
return null;
我真的不确定通过上面的重构会产生什么影响 . 确切地说,我需要知道,对于最终结果使用CompletableFuture是否与使用apply async使用整个CompletableFuture完全相同 . oracle的表单文档,我知道apply async仅用于使用当前执行阶段的默认异步执行工具,但是在请求一个值的completedFuture时它同样适用 . 任何帮助都非常感谢 . 请注意,try catch只是我的方法中的异常处理的一部分,我没有显示 .