一个 Java Optional + Stream 重构的小例子

339 天前
 TWorldIsNButThis
public Optional<MyLog> lastLog(Collection<Long> shopIds) {
    List<Long> allAppIds = StreamUtils.map(appDao.findAll(), App::getId);
    List<MyLog> 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<MyLog> lastLog(Collection<Long> 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.

2307 次点击
所在节点    Java
21 条回复
forgottencoast
215 天前
@nikenidage1
真的,和 C#的 Linq 对比起来 Java 的 Stream 太难用了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/950258

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX