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

如何利用Java Stream API在集合为空时抛出自定义异常?

可以用Stream风格替代原有判断逻辑

当然可以用类似你findByEmail方法里的链式调用风格,来替代原来的if判断块,这里给你两种可行的实现方式:

方式一:用Optional包装列表后判断

把收集好的列表用Optional包装,通过filter过滤非空列表,空列表时直接触发orElseThrow抛异常:

public void create(MultipartFile file) throws Exception {
    List<Employee> employees = CsvHelper.csvToEmployees(file.getInputStream()).stream()
            .map(EmployeeRequestMapper::mapToEntity)
            .collect(Collectors.toList());

    Optional.of(employees)
            .filter(list -> !list.isEmpty())
            .orElseThrow(() -> new NoSuchElementFoundException(NOT_CONTAINS_EMPLOYEE));

    employeeRepository.saveAll(employees);
}

方式二:用collectingAndThen收集器直接在Stream链中处理

这种方式更贴合Stream的链式操作逻辑,在收集列表的同时完成空判断,不用单独拆分步骤:

public void create(MultipartFile file) throws Exception {
    List<Employee> employees = CsvHelper.csvToEmployees(file.getInputStream()).stream()
            .map(EmployeeRequestMapper::mapToEntity)
            .collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
                if (list.isEmpty()) {
                    throw new NoSuchElementFoundException(NOT_CONTAINS_EMPLOYEE);
                }
                return list;
            }));

    employeeRepository.saveAll(employees);
}

两种方式都能达到和原代码一样的效果,且保持了和你findByEmail方法一致的链式调用风格,避免了单独的if判断块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:24:25