嵌套for循环的Java 8替代方法

时间:2020-02-06 15:58:26

标签: java arrays collections java-8 java-stream

我有以下代码段,不知道是否以及如何用Java-streams / Java 8 API替换它

List<Borrower> borrowers = creditcomplex.getBorrowers();
for (Borrower borrower : borrowers) {
    List<Facility> facilities = borrower.getFaciliies();
    for (Facility facility : facilities) {
        List<RepaymentSchedule> repaymentScheduleList = facility.getrepaymentSchedule();
        if (repaymentScheduleList != null) {
            for (RepaymentSchedule repaymentschedule : repaymentScheduleList) {
                double[] repayment = 
                    amortizationService.calculateAmortizationSchedule(repaymentschedule);
                double[] drawdown = 
                    amortizationService.calculateRepaymentSchedule(repaymentschedule);
                double[] outstandingProfie = amortizationService
                        .calculateOutstandingSchedule(repaymentschedule);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:4)

您可以使用flatMap

creditcomplex.getBorrowers().stream()
    .flatMap(b -> b.getFaciliies().stream())
    .flatMap(f -> Optional.ofNullable(f.getrepaymentSchedule()).stream())
    .forEach(repaymentschedule -> {
            double[] repayment = 
                amortizationService.calculateAmortizationSchedule(repaymentschedule);
            double[] drawdown = 
                amortizationService.calculateRepaymentSchedule(repaymentschedule);
            double[] outstandingProfie = amortizationService
                    .calculateOutstandingSchedule(repaymentschedule);
    });

P.S.1:请注意,Optional#stream出现在Java 9中,您可能需要使用:

optional.map(Stream::of).orElseGet(Stream::empty)

它取自here

PS2:您在forEach中所做的操作没有任何效果(您在内部声明和初始化数组,但是不能在循环外部使用它们。我将代码留在了其中,因为它可以被嵌套元素上的任何计算所取代。

P.S.3:返回null而不是空列表很容易出错,通常最好选择空列表。

答案 1 :(得分:1)

未经测试,但应该大致

List<RepaymentSchedule> repaymentSchedules = creditcomplex.getBorrowers().stream()
    .flatMap(borrower -> borrower.getFacilities().stream())
    .map(facility -> facility.getrepaymentSchedule())
    .filter(repaymentScheduleList -> repaymentScheduleList != null)
    .flatMap(repaymentScheduleList -> repaymentScheduleList.stream())
    .collect(Collectors.toList());

将是一回事,从这里您可以创建数组。

或者,您可以省略.collect()代替

.forEach(repaymentSchedule -> {
    double[] repayment = 
                amortizationService.calculateAmortizationSchedule(repaymentschedule);
    double[] drawdown = 
                amortizationService.calculateRepaymentSchedule(repaymentschedule);
    double[] outstandingProfie = amortizationService
                    .calculateOutstandingSchedule(repaymentschedule);
});