【问题标题】:Java Stream processing with if / checking stream state使用 if / 检查流状态的 Java 流处理
【发布时间】: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 状态而不终止它?

【问题讨论】:

标签: java api lambda functional-programming java-stream


【解决方案1】:

下面的代码有点难看,但可以按你的意愿工作。

首先我们需要计算匹配的客户代理数量,然后尝试找到第一个匹配的供应商。如果没有匹配则抛出异常,但是在这里您将检查原因是否是没有找到代理客户以便抛出正确的 excaption。

AtomicInteger countAgencyMatches = new AtomicInteger(0);

allCustomers.stream()
        .filter(customer -> {
            if (customer.getAgency().equals(agency)) {
                countAgencyMatches.incrementAndGet();
                return true;
            }

            return false;
        })
        .filter(customer -> customer.getSupplier().equals(supplier))
        .findFirst()
        .orElseThrow(() -> {
            if (countAgencyMatches.get() == 0) {
                return new AgencyNotSupportedException(agency);
            }

            return new SupplierNotSupportedException(supplier);
        });

【讨论】:

    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多