Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an Immediately Invoked Anonymous Function for Java? [duplicate]

Tags:

java

lambda

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;
}();
like image 246
Dylanthepiguy Avatar asked Aug 23 '16 04:08

Dylanthepiguy


1 Answers

No because lambdas need a target type. The best you can do is cast the expression:

Item similarItem = ((Supplier<Item>) (() -> {
    for (Item i : POSSIBLE_ITEMS) {
        if (i.name.equals(this.name)) return i;
    }
    return null;
})).get();

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:

Item similarItem = POSSIBLE_ITEMS.stream()
                                 .filter(i -> i.name.equals(this.name))
                                 .findFirst()
                                 .orElse(null);

The above code assumes that POSSIBLE_ITEMS is a Collection, likely a List. If it is an array, use this instead:

Item similarItem = Arrays.stream(POSSIBLE_ITEMS)
                         .filter(i -> i.name.equals(this.name))
                         .findFirst()
                         .orElse(null);
like image 199
lazy dog Avatar answered Oct 16 '22 09:10

lazy dog