java 什么都不做的 Lambda

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30108450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:30:09  来源:igfitidea点击:

Lambda that does absolutely nothing

javalambdajava-8runnable

提问by Rien

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

我需要一个Runnable什么都不做的函数式接口的 lambda 表达式。我以前有个方法

private void doNothing(){
    //Do nothing
}

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

然后使用this::doNothing. 但我找到了一种更短的方法来做到这一点。

回答by Eddú Meléndez

For Runnable interface you should have something like that:

对于 Runnable 接口,你应该有这样的东西:

Runnable runnable = () -> {};

Where:

在哪里:

  • ()because run method doesn't receive args
  • {}body of run method which in this case is empty
  • ()因为 run 方法不接收参数
  • {}run 方法的主体,在这种情况下为空

After that, you can call the method

之后,您可以调用该方法

runnable.run();

回答by Rien

The lambda expression I use now is:

我现在使用的 lambda 表达式是:

() -> {}

回答by emanuel07

Guava- Runnables.doNothing();

番石榴-Runnables.doNothing();