双鸭山市网站建设_网站建设公司_数据统计_seo优化
2025/12/24 0:27:22 网站建设 项目流程

不可以直接对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; }
  1. 使用 @NonNull 注解(如 Lombok 或 javax.annotation)

  2. 在方法内部处理空值,确保调用方不需要处理 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。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询