What does ()->{} represent in java?. Any help would be highly appreciated.
-
1Possible duplicate of [What does the arrow operator, '->', do in Java?](http://stackoverflow.com/questions/15146052/what-does-the-arrow-operator-do-in-java) – Suraj Rao Apr 29 '17 at 06:38
-
2You should at least show us this in the context of some actual code. – Tim Biegeleisen Apr 29 '17 at 06:38
-
2Read up on Java 8 Lambdas – Dawood ibn Kareem Apr 29 '17 at 06:41
-
It's a "lambda", a way of representing functions, or in Java's case, anonymous implementations of functor interfaces. – Lew Bloch Apr 29 '17 at 06:43
-
Extremely sorry for that . I have seen this operator in many function calls, so I thought it is general one. Latest encounter in the following function call executorService.execute(() -> { sqs.receiveMessage(); processMessage(); }); – Vivek Kumar Apr 29 '17 at 06:43
-
It is "a general one". Isn't it? – Lew Bloch Apr 29 '17 at 06:44
2 Answers
It's a lambda expression, basically a concise way of writing a function. ()->{}
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
}
};

- 7,020
- 2
- 39
- 70
-
-
2It could actually be useful as a NOOP default value for something. E.g. an optional callback because if the default is `()->{}` then you don't need to check for null. Basically the Null Object pattern – takteek Apr 29 '17 at 07:03
Let's consider old way of writing functions(i.e methods) in 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).
in those case we use syntax like (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. you can see here
now lets see about syntax (a,b) ->{ return a + b};
(a,b) are arguments to function;
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

- 1
- 1

- 2,058
- 1
- 15
- 35