Is there a way to make the code below simpler and shorter?
boolean clicked = false;
for (WebElement anchor : anchorLinksForProducts) {
if (anchor.getAttribute("href").contains(id)) {
anchor.click();
clicked = true;
break;
}
}
Assert.assertTrue(clicked, "Could not find a valid product link with id : " + id);
A refinement to @Mureinik's answer.
anchorLinksForProducts.stream()
.filter(a -> a.getAttribute("href").contains(id))
.findFirst()
.ifPresentOrElse(
WebElement::click,
() -> fail("Could not find a valid product link with id : " + id)
);
There's a little more overhead in this code, but that is always the case with streams and not a problem if it is test code.