0
for (String winHandle : driver.getWindowHandles()) 
{
    driver.switchTo().window(winHandle); 
}

Can we rewrite this using Lambda Expression?

1
  • Is it really required to execute driver.switchTo() again in every loop iteration? If not, you can simply use driver.getWindowHandles().forEach(driver.switchTo()::window) Commented Feb 10, 2017 at 17:38

2 Answers 2

2

I would go for

driver.getWindowHandles().forEach(windowHandle -> {
    driver.switchTo().window(windowHandle);
});

which is equivalent to:

for(String windowHandle : driver.getWindowHandles()) {
    driver.switchTo().window(windowHandle);
}

forEach method calls can be used for Collections. You can go parallel with the usage of forEach together with parallelStream. Read further.

Sign up to request clarification or add additional context in comments.

2 Comments

Some explanation might help.
@Pavlo, added explanation.
0

You can do it like

driver.getWindowHandles().stream().forEach((i) -> {
     driver.switchTo().window(i);
});

or like

driver.getWindowHandles().parallelStream().forEachOrdered((i) -> {
     driver.switchTo().window(i);
});

Stream api offers other possibilities that can make your life easier.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.