请帮我把这段代码优化成 stream的方式 List<PCheckStatistic> days = checkStatisticMapper.selectDayWorkOrderStatistics(); List<PCheckStatistic> months = checkStatisticMapper.selectMonthWorkOrderStatistics(); for (PCheckStatistic day: days) { for(PCheckStatistic month: months){ day.setnM01(month.getnM01()); day.setnM02(month.getnM02()); day.setnM03(month.getnM03()); day.setnM04(month.getnM04()); day.setnM05(month.getnM05()); day.setnM06(month.getnM06()); day.setnM07(month.getnM07()); day.setnM08(month.getnM08()); } }
时间: 2024-03-12 22:46:56 浏览: 85
List<Long>转一维数组 Long[](csdn)————程序.pdf
5星 · 资源好评率100%
可以使用Java 8引入的Stream API来优化这段代码,代码如下:
```
List<PCheckStatistic> days = checkStatisticMapper.selectDayWorkOrderStatistics();
List<PCheckStatistic> months = checkStatisticMapper.selectMonthWorkOrderStatistics();
days.forEach(day -> {
months.stream()
.findFirst()
.ifPresent(month -> {
day.setnM01(month.getnM01());
day.setnM02(month.getnM02());
day.setnM03(month.getnM03());
day.setnM04(month.getnM04());
day.setnM05(month.getnM05());
day.setnM06(month.getnM06());
day.setnM07(month.getnM07());
day.setnM08(month.getnM08());
});
});
```
使用Stream来对月份进行遍历,然后使用findFirst()寻找第一个元素进行赋值。由于在循环体内部对集合months只需要访问第一个元素,所以使用findFirst()方法可以提高效率。
阅读全文