Java Stream API: Throwing custom exception for empty list

Viewed 108

I have the following service method:

public void create(MultipartFile file) throws Exception {
      List<Employee> employees = CsvHelper.csvToEmployees(file.getInputStream()).stream()
              .map(EmployeeRequestMapper::mapToEntity)
              .collect(Collectors.toList());
     
      // Can I use Stream and throw exception if employees is empty
      if (employees.isEmpty()) {
          throw new NoSuchElementFoundException(NOT_CONTAINS_EMPLOYEE);
      }

      employeeRepository.saveAll(employees);
}

Here I read CSV file and if there is no record, throw my custom NoSuchElementFoundException exception.

However, regarding to if block, I am not sure if there is a proper way using Java Stream as I use in the following example:

public EmployeeDto findByEmail(String email) {
    return employeeRepository.findByEmail(email)
            .map(EmployeeDto::new)
            .orElseThrow(() -> new NoSuchElementFoundException(NO_ITEM_FOUND));
}

So, can I apply similar one to the create() method?

1 Answers

You can use the following, which will be applied after the result is collected on the list and it will check if the result list is empty and if that is the case it will throw the exception

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