71

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.

Rien
  • 1,466
  • 1
  • 12
  • 16

3 Answers3

87

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();
Eddú Meléndez
  • 5,373
  • 1
  • 25
  • 28
46

The lambda expression I use now is:

() -> {}
Rien
  • 1,466
  • 1
  • 12
  • 16
17

Guava - Runnables.doNothing();

emanuel07
  • 686
  • 10
  • 25
  • 3
    It's madness to include a library for a 6 character expression. Even if you already had Guava in your dependencies this solution is longer than the simple expression and does not improve readability. – Björn Zurmaar Jun 11 '20 at 21:48
  • 11
    in my opinion it does improve readibility. You do a static import and in the code you just see "doNothing()". The reader wil understand very quickly that you intentionally decided to "do nothing". Ofk adding Guava to classpath just for that would be a waste. – fascynacja Jul 03 '20 at 09:56
  • Add a comment to show you intentionally decided to do nothing. – MeanwhileInHell Aug 20 '21 at 13:42