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<String> getList() {
    return Collections.emptyList(); // 不是 null
    }

    // 不推荐
    public List<String> 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。

相关推荐
侠客行031715 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪15 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚17 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎17 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Yvonne爱编码17 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚17 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂17 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang17 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
琹箐18 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
__WanG18 小时前
JavaTuples 库分析
java