Search code examples
javaseleniumconsumer

Java method that accepts Consumer<WebElement> as parameter - how to use it?


Is there any chance and need to use something like below ?

Could you show examples how to use function thats accepts Consumer WebElement ?

private static void methodThatAcceptsConsumer (Consumer<WebElement> consumer) {
    //something here
}

Solution

  • Consumer is an interface. You can implement it as a real class, a named nested class or as lambda.

    Explicit implementation as class

    class MyWebElementConsumer implements Consumer<WebElement> {
      @Override
      public void accept(final WebElement element) {
        // do something with element
      }
    }
    
    methodThatAcceptsConsumer(new MyWebElementConsumer());
    

    Pass a lambda

    methodThatAcceptsConsumer(element -> {/* do something with element */});