[英]What does ()->{} represent in java?
What does ()->{} represent in java?. ()-> {}在Java中代表什么? Any help would be highly appreciated.
任何帮助将不胜感激。
It's a lambda expression, basically a concise way of writing a function. 这是一个lambda表达式,基本上是一种编写函数的简洁方法。
()->{}
is a function that takes no arguments and does nothing. ()->{}
是一个不带参数也不执行任何操作的函数。 A longer way of writing the same thing: 编写相同内容的更长方法:
new Runnable() {
@Override
public void run() {
// nothing
}
};
Let's consider old way of writing functions(ie methods) in java. 让我们考虑用Java编写函数(即方法)的旧方法。
//lets assume this is inside calculate class
public int sum(int a, int b){
return a+b;
}
in java 8 we have something called lambda's in which we have concept called passing behaviours(methods) to another behaviour(methods). 在Java 8中,我们有一个称为lambda的东西,其中有一个概念称为传递行为(方法)到另一个行为(方法)。
in those case we use syntax like (a,b) -> return a+b
; 在那种情况下,我们使用类似
(a,b) -> return a+b
语法;
BiFunction<Integer,Integer,Integer> sum= (a,b)->{
return a+b;
};
System.out.println(sum.apply(1, 2));
Even we can store Function in a variable and pass to another function. 甚至我们可以将Function存储在变量中并传递给另一个函数。 you can see here
你可以在这里看到
now lets see about syntax (a,b) ->{ return a + b};
现在让我们看一下语法
(a,b) ->{ return a + b};
(a,b) are arguments to function; (a,b)是函数的参数;
and the line of code inside {} represent the behaviour. {}中的代码行代表行为。 -> is to separate both left and right expressions.
->用于分隔左右两个表达式。
you can explore more about java8 and lambda over here 您可以在此处探索有关java8和lambda的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.