2017-10-10 121 views
2

我有一个对象列表和一个数组。我的数组有少量客户选择的ID(字符串)。我的对象有一个属性ID。我想通过一组ID来过滤我的列表。有没有一种方法可以使用谓词或lambda来过滤它?如何用ID数组过滤对象列表?

public class PaymentDueData { 

    private long paymentScheduleId; 
    private String invoiceNumber; 

} 

String [] selectedInvoices; 
+0

您是否只希望包含与选定发票匹配的付款数据,或将其排除? – azurefrog

+0

包含与所选发票匹配的付款数据 – karim

回答

-1

像这样的东西很可能是:

paymentDueDataCollection.stream() 
         .filter(x -> Arrays.stream(selectedInvoices) 
           .anyMatch(y -> y.equals(x.getInvoiceNumber())) 
         .collect(Collectors.toList()); 
+0

如果'paymentDueDataCollection'很大,则每次创建一个新流并执行'.anyMatch()'都可能会产生问题。 – Tet

+0

@当然。如果这是一个性能问题 – Eugene

1

首先,我会变成数组selectedInvoicesSet<String>以提高查询:

HashSet<String> invoices = new HashSet<>(Arrays.asList(selectedInvoices)); 

然后,你需要检查存在元素ID为data.getInvoiceNumber()的集合:

(...) 
    .stream() 
    .filter(data -> invoices.contains(data.getInvoiceNumber())) 
    .collect(Collectors.toList()); 
+0

为什么转换为哈希集?你可以简单地使用它作为流。 –

+0

没错。但为什么不简单地使用Arrays.binarySearch? –

+0

是啊!我在内存方面想。 –