サイモンザック:
(サプライヤーと庁のフィールドを持つ)お客様のリスト、文字列の代理店、文字列のサプライヤー:与えられました。
目標:チェック任意の顧客サポートは、代理店を与えられたとサプライヤーを与えられている場合。
私は二度(二つの値によって)フィルタリングする必要が流れを持っています。ストリームは最初のフィルタリングの後に空の場合、私はそれをチェックして、例外をスローする必要があります。それが空でないなら、私は(それが空でない場合は、再度チェックしと)は、第2のフィルタを介してそれを処理する必要があります。
私はそれが可能だ場合はリストにストリームを収集しないようにしたい(そして、彼らは、端末ですので、私はanyMatchやカウントメソッドを使用することはできません)
現在、私のコードを見てはようなものです:
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);
}
この例では、私は(例えばStringにサプライヤーを解析する)フィルタリングに関するいくつかの技術的な詳細をスキップ。
そして、私はこのような何かを達成したいです:
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の機能はありますか?
E.ベタンソス:
あなたが望むように以下のコードは、ビット醜いが、作品です。
まず、と一致してどのように多くのお客様の代理カウントして、最初に見つかった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);
});