我有一个对象列表和一个数组。我的数组有少量客户选择的ID(字符串)。我的对象有一个属性ID。我想通过一组ID来过滤我的列表。有没有一种方法可以使用谓词或lambda来过滤它?如何用ID数组过滤对象列表?
public class PaymentDueData {
private long paymentScheduleId;
private String invoiceNumber;
}
String [] selectedInvoices;
我有一个对象列表和一个数组。我的数组有少量客户选择的ID(字符串)。我的对象有一个属性ID。我想通过一组ID来过滤我的列表。有没有一种方法可以使用谓词或lambda来过滤它?如何用ID数组过滤对象列表?
public class PaymentDueData {
private long paymentScheduleId;
private String invoiceNumber;
}
String [] selectedInvoices;
首先,我会变成数组selectedInvoices
成Set<String>
以提高查询:
HashSet<String> invoices = new HashSet<>(Arrays.asList(selectedInvoices));
然后,你需要检查存在元素ID为data.getInvoiceNumber()
的集合:
(...)
.stream()
.filter(data -> invoices.contains(data.getInvoiceNumber()))
.collect(Collectors.toList());
为什么转换为哈希集?你可以简单地使用它作为流。 –
没错。但为什么不简单地使用Arrays.binarySearch? –
是啊!我在内存方面想。 –
您是否只希望包含与选定发票匹配的付款数据,或将其排除? – azurefrog
包含与所选发票匹配的付款数据 – karim