This question already has an answer here:
For example, I might want to do an assignment like this (in JavaScript):
var x = (function () {
// do some searching/calculating
return 12345;
})();
And in Java, how can I do something similar with Lambdas? The compiler does not like something like this:
Item similarItem = () -> {
for (Item i : POSSIBLE_ITEMS) {
if (i.name.equals(this.name)) return i;
}
return null;
}();
No because lambdas need a target type. The best you can do is cast the expression:
You must use the correct Functional Interface for your particular lambda. As you can see, it is very clunky and not useful.
UPDATE
The above code is a direct translation of the JavaScript code. However, converting code directly will not always give the best result.
In Java you'd actually use streams to do what that code is doing:
The above code assumes that
POSSIBLE_ITEMS
is aCollection
, likely aList
. If it is an array, use this instead: