【发布时间】:2020-07-14 16:03:05
【问题描述】:
给定:客户列表(带有供应商和代理字段)、字符串代理、字符串供应商。
目标:检查是否有任何客户支持给定的代理商和给定的供应商。
我有一个需要过滤两次的流(按两个值)。 如果第一次过滤后流为空,我需要检查它并抛出异常。如果它不为空,我需要通过第二个过滤器对其进行处理(然后再次检查它是否为空)。
如果可能的话,我想避免将流收集到列表中(我不能使用 anyMatch 或 count 方法,因为它们是终端)
目前我的代码如下:
void checkAgencySupplierMapping(String agency, String supplier) {
List<Customers> customersFilteredByAgency = allCustomers.stream()
.filter(customer -> customer.getAgency().equals(agency))
.collect(toList());
if (customersFilteredByAgency.isEmpty()) throw new AgencyNotSupportedException(agency);
customersFilteredByAgency.stream()
.filter(customer -> customer.getSupplier().equals(supplier))
.findFirst().orElseThrow(() -> throw new SupplierNotSupportedException(supplier);
}
在这个例子中,我跳过了一些关于过滤的技术细节(例如,将供应商解析为字符串)。
我想实现这样的目标:
void checkAgencySupplierMapping(String agency, String supplier) {
allCustomers.stream()
.filter(customer -> customer.getAgency().equals(agency))
.ifEmpty( () -> throw new AgencyNotSupportedException(agency) )
.filter( customer -> customer.getSupplier().equals(supplier)
.ifEmpty( () -> throw new SupplierNotSupportedException(supplier); // or findFirst().orElseThrow...
}
是否有任何 Java 8 功能可以让我检查我的 Stream 状态而不终止它?
【问题讨论】:
-
您无法检查
Streamsize without a terminal operation。所以你的第一个代码块很简单。
标签: java api lambda functional-programming java-stream