优化以下代码List<SalaryBillListOfPermits> salaryBillListOfPermitsList = new ArrayList<>(); for (OnWorkingEmployeeVO onWorkingEmployee : onWorkingEmployees) { Integer numbs = hrmSalaryBillRecordDAO.getCountByCorpIdAndUserId(param.getCorpId(), onWorkingEmployee.getUserId()); SalaryBillListOfPermits salaryBillListOfPermits = new SalaryBillListOfPermits(); salaryBillListOfPermits.setNumbs(numbs); salaryBillListOfPermits.setDeptName(onWorkingEmployee.getMainDeptName()); salaryBillListOfPermits.setJobNumber(onWorkingEmployee.getEmpJobNumber()); salaryBillListOfPermits.setPersonId(onWorkingEmployee.getUserId()); salaryBillListOfPermits.setPersonName(onWorkingEmployee.getName()); salaryBillListOfPermitsList.add(salaryBillListOfPermits); }
时间: 2024-03-05 21:54:03 浏览: 62
List<Bean>转换为List<Map>
可以优化的地方有以下几点:
1. 减少数据库查询次数:可以使用一条 SQL 语句查询出所有员工的薪资单数量,避免每个员工都要单独查询一次。比如可以使用 `IN` 关键字将所有员工的 ID 拼接成一个字符串,然后在 SQL 语句中使用 `WHERE user_id IN (id1, id2, ...)` 来查询。
2. 使用 stream API:可以使用 Java 8 引入的 stream API 来简化代码。比如可以使用 `stream().map()` 将 `onWorkingEmployees` 转换成 `SalaryBillListOfPermits` 列表,然后使用 `collect(Collectors.toList())` 将其收集起来。
优化后的代码如下:
```java
List<Integer> userIds = onWorkingEmployees.stream()
.map(OnWorkingEmployeeVO::getUserId)
.collect(Collectors.toList());
Map<Integer, Integer> salaryBillCounts = hrmSalaryBillRecordDAO.getCountsByCorpIdAndUserIds(param.getCorpId(), userIds);
List<SalaryBillListOfPermits> salaryBillListOfPermitsList = onWorkingEmployees.stream()
.map(onWorkingEmployee -> {
Integer numbs = salaryBillCounts.getOrDefault(onWorkingEmployee.getUserId(), 0);
SalaryBillListOfPermits salaryBillListOfPermits = new SalaryBillListOfPermits();
salaryBillListOfPermits.setNumbs(numbs);
salaryBillListOfPermits.setDeptName(onWorkingEmployee.getMainDeptName());
salaryBillListOfPermits.setJobNumber(onWorkingEmployee.getEmpJobNumber());
salaryBillListOfPermits.setPersonId(onWorkingEmployee.getUserId());
salaryBillListOfPermits.setPersonName(onWorkingEmployee.getName());
return salaryBillListOfPermits;
})
.collect(Collectors.toList());
```
阅读全文