用Lambda表达式替换列表迭代逻辑

时间:2018-08-08 10:02:44

标签: java lambda java-8

我下面的代码可以遍历列表,检查特定值,然后终止循环。如果可以的话,能否请您提出一种使用lambda表达式的更好方法?

            for(InvoiceLine invoiceLine : inputInvoice.getInvoiceLines()) {
                Object flag = invoiceLine.getTransientField("ApproveInvoiceLine");
                if(flag != null && ((Boolean)flag)) {
                    approveInv = true;
                    break;
                }
            }

2 个答案:

答案 0 :(得分:3)

boolean approveInv = inputInvoice.getInvoiceLines()
                           .stream()
                           .map(x -> x.getTransientField("ApproveInvoiceLine"))
                           .anyMatch(x -> x != null && ((Boolean)x));

答案 1 :(得分:0)

 boolean approveInv = inputInvoice.getInvoiceLines().stream()
             .filter(i -> invoiceLine.getTransientField("ApproveInvoiceLine")!=null)
             .filter(i -> ((Boolean)invoiceLine.getTransientField("ApproveInvoiceLine"))==true)
             .findFirst()
             .isPresent();