3
有人可能有任何想法如何將其替換爲stream()
?更改兩個foreach到一個流
for (Customer customer : customers) {
if (customer.getProducts() != null && customer.getProducts().getProduct() != null) {
for (Product product : customer.getProducts().getProduct()) {
if (product.getId().equals(productId)) {
return Optional.of(product);
}
}
}
}
我知道,第二的foreach我可以替換爲:
customer.getProducts().getProduct().stream().filter(a -> a.getId().equals(productId)).findAny();
但我怎麼能更換一個流都foreachs?
查找到flatMap() –
大概[該線程的重複](https://stackoverflow.com/questions/34406744/refactoring-a-nested-foreach-into-java-8-stream) – GuyKhmel