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?