You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何无需if/else判断即可根据null校验将bean添加到不同列表

空值分支替代方案

下面给出几种完全等价于原有逻辑、不需要写if/else的实现方式:


方案1:Optional函数式判断(推荐,Java 9+适用)

利用JDK自带的Optional类的ifPresentOrElse方法承载双分支逻辑,写法符合函数式编程规范,可读性高:

List<String> successfullLIst = new ArrayList<>();
List<String> failedList = new ArrayList<>();

Optional.ofNullable(saveindb(accountId))
        .ifPresentOrElse(
            myBean -> successfullLIst.add(myBean.getAccountid()),
            () -> failedList.add(accountId)
        );

注:ifPresentOrElse为Java 9新增API,Java 8环境可改用下方三元运算符方案


方案2:三元运算符简化(全版本适用)

因为List.add()方法固定返回boolean类型,可直接用三元运算符承接两个分支的执行逻辑,代码更精简:

List<String> successfullLIst = new ArrayList<>();
List<String> failedList = new ArrayList<>();

MyBean myBean = saveindb(accountId);
// 仅做分支执行,返回的boolean值可根据业务需要决定是否接收
boolean unused = myBean != null ? 
    successfullLIst.add(myBean.getAccountid()) : 
    failedList.add(accountId);

方案3:批量场景分区处理

如果需要批量处理多个账号ID,可以结合Stream的partitioningBy收集器一次性拆分成功/失败列表,全程无显式if/else:

List<String> accountIds = // 待入库的账号ID集合
Map<Boolean, List<String>> resMap = accountIds.stream()
        .map(id -> {
            MyBean bean = saveindb(id);
            return bean != null ? 
                Map.entry(true, bean.getAccountid()) : 
                Map.entry(false, id);
        })
        .collect(Collectors.partitioningBy(
            Map.Entry::getKey,
            Collectors.mapping(Map.Entry::getValue, Collectors.toList())
        ));

List<String> successfullLIst = resMap.get(true);
List<String> failedList = resMap.get(false);

内容的提问来源于stack exchange,提问作者Debo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 18:33:01