Lambda that does absolutely nothing

JavaLambdaJava 8Runnable

Java Problem Overview


I needed to have a lambda expression of the functional interface Runnable that did nothing. I used to have a method

private void doNothing(){
    //Do nothing
}

and then use this::doNothing. But I've found an even shorter way to do this.

Java Solutions


Solution 1 - Java

For Runnable interface you should have something like that:

Runnable runnable = () -> {};

Where:

  • () because run method doesn't receive args
  • {} body of run method which in this case is empty

After that, you can call the method

runnable.run();

Solution 2 - Java

The lambda expression I use now is:

() -> {}

Solution 3 - Java

Guava - Runnables.doNothing();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRienView Question on Stackoverflow
Solution 1 - JavaEddú MeléndezView Answer on Stackoverflow
Solution 2 - JavaRienView Answer on Stackoverflow
Solution 3 - Javaemanuel07View Answer on Stackoverflow