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。

相关推荐
折哥的程序人生 · 物流技术专研10 小时前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
researcher-Jiang11 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
夜雪一千11 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
西门吹-禅12 小时前
java springboot N+1问题
java·开发语言·spring boot
DLYSB_12 小时前
生命通道:如何用 HIS 医疗系统直连网络声光终端,打造“零延误”的危急值响应网关?
java·网络·数据库·报警灯
weixin_BYSJ198713 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
AI小码13 小时前
LLM 应用的缓存工程:当每次 API 调用都在燃烧成本
java·人工智能·spring·计算机·llm·编程·api
Hui Baby13 小时前
Spring Security
java·后端·spring
IT笔记14 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
我才是银古15 小时前
构建 Java GIS 工具库:从碎片化 API 到统一抽象的设计实践
java·gis·geotools·gdal·esri