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

将Optional<Department>转为List<Department>的代码修改疑问

问题解答

疑问1解答

原返回Optional.empty()的位置改为返回new LinkedList<>()是正确的,但更推荐用Collections.emptyList()——这是JDK提供的不可变空列表,无需创建新对象,性能更优。如果业务场景需要后续对返回的列表执行添加元素等修改操作,用new LinkedList<>()也完全没问题。

疑问2解答

List<Department>没有isPresent()方法,原来的Optional.isPresent()是判断是否存在非空值,对应到List上,需要判断列表不为null且包含元素,替换写法为:

if (existing != null && !existing.isEmpty())

先判null是因为get(department_ID)可能返回null,避免空指针异常;再判isEmpty()是确认列表里有有效数据。


修改后的完整代码

public List<Department> delete(String department_ID) {
    if ((department_ID == null) || (department_ID.isEmpty())) {
        return Collections.emptyList(); // 推荐用不可变空列表,也可保留new LinkedList<>()
    }

    List<Department> existing = get(department_ID);
    if (existing != null && !existing.isEmpty()) {
        String sql = "DELETE employee.*, department.* " + "FROM employee, department "
            + "WHERE employee.department_ID = :department_ID AND department.department_ID = :department_ID;";

        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("department_ID", department_ID);

        int rows = jdbcTemplate.update(sql, parameters);
        if (rows > 0) {
            return existing;
        }
    }
    return Collections.emptyList(); // 同样推荐用Collections.emptyList()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:35:35