java list=null,可以stream吗

不可以直接对 null列表进行 Stream 操作 ,会抛出 NullPointerException

解决方案:

1. 使用 Optional 包装(推荐)

复制代码
List<String> list = null;
List<String> result = Optional.ofNullable(list)
    .orElse(Collections.emptyList())
    .stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

2. 使用 Collections.emptyList() 替代 null

复制代码
List<String> list = null;
List<String> result = (list == null ? Collections.emptyList() : list)
    .stream()
    .filter(Objects::nonNull)
    .collect(Collectors.toList());

3. Java 9+ 的 Stream.ofNullable(单个元素)

复制代码
// 注意:这是针对单个元素,不是整个列表
Stream<String> stream = Stream.ofNullable(list)
    .flatMap(List::stream);

4. 自定义工具方法

复制代码
public static <T> Stream<T> safeStream(List<T> list) {
    return list == null ? Stream.empty() : list.stream();
}

// 使用
List<String> result = safeStream(list)
    .map(String::toLowerCase)
    .collect(Collectors.toList());

5. 使用第三方库

复制代码
// Apache Commons Collections
List<String> result = CollectionUtils.emptyIfNull(list)
    .stream()
    .collect(Collectors.toList());

最佳实践建议:

  1. 避免返回 null 列表,尽量返回空集合:

    // 推荐
    public List getList() {
    return Collections.emptyList(); // 不是 null
    }

    // 不推荐
    public List getList() {
    return null;
    }

  2. 使用 @NonNull 注解(如 Lombok 或 javax.annotation)

  3. 在方法内部处理空值,确保调用方不需要处理 null

示例:安全处理

复制代码
List<String> processList(List<String> input) {
    return Optional.ofNullable(input)
        .orElseGet(Collections::emptyList)
        .stream()
        .filter(Objects::nonNull)
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .collect(Collectors.toList());
}

核心原则 :在调用 stream()之前,确保列表不为 null。

相关推荐
落苜蓿蓝18 小时前
Java 循环中对象复用导致属性覆盖?从 JVM 内存模型讲解原因
java·jvm·python
weixin_4407841118 小时前
Android基础知识汇总
android·java·android studio
布鲁飞丝18 小时前
从零实现富文本编辑器#-浏览器选区与编辑器选区模型同步
java·前端·编辑器
鱼子星_19 小时前
【C++】深入剖析list:list及其双向迭代器实现
开发语言·数据结构·c++·笔记·stl·list
脚踏实地皮皮晨19 小时前
003002004_WPF Panel 基类 官方类定义
开发语言·windows·算法·c#·wpf·visual studio
jun_bai19 小时前
使用java安全的移动文件
java
caishenzhibiao19 小时前
市场同步系统 同花顺期货通指标
java·c语言·c#
Devin~Y19 小时前
从本地生活电商到 AI RAG:互联网大厂 Java 面试场景完整实战
java·spring boot·redis·elasticsearch·spring cloud·kafka·rag
sukalot19 小时前
windows网络适配器驱动开发-双 STA 连接(下)
windows·驱动开发·stm32
520拼好饭被践踏19 小时前
JAVA+Agent学习day25
java·开发语言·学习