List<ExpenseStatisticsDTO> expenseFlightByDept = travelExpensesRepository.getExpenseFlightByDept(expenseStatisticsDTO); List<ExpenseStatisticsDTO> expenseTrainByDept = travelExpensesRepository.getExpenseTrainByDept(expenseStatisticsDTO); List<ExpenseStatisticsDTO> expenseHotelByDept = travelExpensesRepository.getExpenseHotelByDept(expenseStatisticsDTO); List<ExpenseStatisticsDTO> expenseZSByDept = travelExpensesRepository.getExpenseZSByDept(expenseStatisticsDTO); List<ExpenseStatisticsDTO> expenseJTByDept = travelExpensesRepository.getExpenseJTByDept(expenseStatisticsDTO); List<ExpenseStatisticsDTO> expenseBTByDept = travelExpensesRepository.getExpenseBTByDept(expenseStatisticsDTO); List<ExpenseStatisticsDTO> expenseOtherByDept = travelExpensesRepository.getExpenseOtherByDept(expenseStatisticsDTO); Java把以上List合并成一个List,按ExpenseStatisticsDTO对象中structNo相同的情况下,则把totalPrice相加,最后返回List<ExpenseStatisticsDTO>
时间: 2024-01-13 18:02:34 浏览: 70
List<Long>转一维数组 Long[](csdn)————程序.pdf
5星 · 资源好评率100%
可以使用Java 8中的Stream API来实现List合并和按照structNo相同的情况下把totalPrice相加的操作。实现代码如下:
```java
List<ExpenseStatisticsDTO> mergedList = Stream.of(expenseFlightByDept, expenseTrainByDept, expenseHotelByDept, expenseZSByDept, expenseJTByDept, expenseBTByDept, expenseOtherByDept)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(ExpenseStatisticsDTO::getStructNo, Collectors.reducing(
new ExpenseStatisticsDTO("", "", 0.0),
(a, b) -> new ExpenseStatisticsDTO(b.getStructNo(), b.getStructName(), a.getTotalPrice() + b.getTotalPrice()),
(a, b) -> new ExpenseStatisticsDTO(b.getStructNo(), b.getStructName(), a.getTotalPrice() + b.getTotalPrice())
)))
.values()
.stream()
.sorted(Comparator.comparing(ExpenseStatisticsDTO::getStructNo))
.collect(Collectors.toList());
```
上述代码中,首先将多个List加入到一个Stream中,然后通过flatMap方法将多个Stream扁平化为一个Stream。接着使用groupingBy方法按structNo分组,使用reducing方法将同一组的ExpenseStatisticsDTO对象的totalPrice相加,并将结果转换为一个新的ExpenseStatisticsDTO对象。最后通过values方法取出所有的分组结果,通过sorted方法按照structNo排序,并通过collect方法将结果转换为List,即可得到合并后的List。
阅读全文