我刚刚开始在一个新项目中使用Java 8,现在我正尝试转换一些旧代码。

我正在尝试转换为以下代码片段。这是用于前端测试的,可以简单地进行比较,如果productElements中是否有正确数量的产品(代码):

for (Product product : products) {
    boolean productFound = false;
    for (ProductWebElement productElement : productElements) {
        if (productElement.getProductCode().equals(product.getCode())) {
            Assert.assertEquals(product.getQuantity(), productElement.getQuantity());
            productFound = true;
            break;
        }
    }
    // This is optional - can be ignored
    if (!productFound) {
        fail("Product: " + product.getCode() + " not found!");
    }
}


Product只是普通数据类(String productCode, int quantity

ProductWebElementFluentWebElement的扩展对象-或只是具有某些其他属性的对象。

我试图延长
Java 8: More efficient way of comparing lists of different types?
但我不知道该怎么做。有谁知道如何用Java 8语法做到这一点?

最佳答案

您可以编写以下代码:

products.forEach(p -> {
    ProductWebElement productElement = productElements.stream().filter(
        pe -> pe.getProductCode().equals(p.getCode())
    ).findAny().orElseThrow(() -> new AssertionError("Product: " + p.getCode() + " not found!"));
    Assert.assertEquals(p.getQuantity(), productElement.getQuantity());
});


对于您的每个产品,我们都会尝试找到任何匹配的ProductElement(具有相同的产品代码)。

如果未找到,则抛出AssertionError。如果找到一个,则可以断言数量相同。

10-04 12:37
查看更多