List allAppIds = StreamUtils.map(appDao.findAll(), App::getId);
List logs = new ArrayList();
shopIds.forEach(sid -> {
allAppIds.forEach(aid -> {
MyLog lastLog = logDao.findLast(aid, sid, null, LocalDate.now().plusDays(1));
if (Objects.nonNull(lastLog)) {
logs.add(lastLog);
}
});
});
if (CollectionUtils.isEmpty(logs)) {
return Optional.empty();
}
logs.sort(Comparator.comparing(MyLog::getTime));
return Optional.of(Iterables.getLast(logs));
}
public Optional lastLog(Collection shopIds) {
if (shopIds.isEmpty()) {
return Optional.empty();
}
var allAppIds = appDao.findAllId();
var end = LocalDate.now().plusDays(1);
return shopIds.stream()
.flatMap(shopId -> allAppIds.stream().flatMap(appId -> logDao.findLast(appId, shopId, end).stream()))
.max(Comparator.comparing(MyLog::getTime));
}
我们用的 java 11 ,部分方法 java 8 可能没有
类名和方法名有做部分处理
原来的方法不知道为什么主动用了 optional 但还是写成这么一大坨
调整后的 early return 其实也能合并到 optional 里串起来,不过想想还是算了,反倒显得更麻烦
另外这个 max 是 idea 自动提示的调整,一开始是照着原方法的思路写成 sorted + findFirst
idea 很多 warning 都可以很方便的 alt + enter 直接重构掉
copilot 锐评:
Overall, the refactored implementation is more concise and readable than the original implementation, and makes use of functional programming constructs to achieve the same result. It also avoids the use of nested loops, which can be harder to read and understand.
optional, mylog, lastlog, return