I suppose that what you mean is to change the external iteration over your collection into internal iteration using lambda expression.
You are probably struggling with the need to finish abruptly the internal forEach()
loop.
According to the documentation for Iterable.forEach()
:
Performs the given action for each element of the Iterable
until all elements have been processed or the action throws an exception... Exceptions thrown by the action are relayed to the caller.
So instead of using break
, you throw an exception which will immediately break the internal loop.
The code will be something like this - I cannot say I like it but it works. You create your own class BreakException
which extends RuntimeException
.
try {
word.forEach(symbol -> {
sendKeys(symbol);
if (isElementVisible(word)) { // see N.B.
clickByVisibleText(word);
throw new BreakException();
}
});
}
catch (BreakException e) {
// here you know that your condition has been fulfilled at least once
}
Notice that the try...catch
is not around the lambda expression, but rather around the whole forEach()
method. To make it more visible, see the following transcription of the code which shows it more clearly:
Consumer<? super String> findElement = symbol -> {
sendKeys(symbol);
if (isElementVisible(word)) { // see N.B.
clickByVisibleText(word);
throw new BreakException();
}
});
try {
word.forEach(findElement);
}
catch (BreakException e) {
// here you know that your condition has been fulfilled at least once
}
N.B.: Please re-consider also your code
if (isElementVisible(word)) {
clickByVisibleText(word);
throw new BreakException();
}
It looks quite suspicious. Here in the middle of the loop you keep referring to the whole collection word
which stinks.