javamethodslambdainference

How Java process Method Inference Lambda Expression as method parameter?


In code below, method inference iF::apply is put into a Map in class Context.

But when using get method on the Map with iF::apply, we get null. Why?

Here is the debug info with IDEA:

enter image description here

Below is the code:

    public void test() {
        Context context = new Context();
        IF iF = new IF();
        context.put(iF::apply, 100);
        Integer v = context.get(iF::apply);
        System.out.println(v);
    }

class IF implements Function<String, Integer> {
    @Override
    public Integer apply(String s) {
        return 200;
    }
}

class Context {
    private Map<Function, Object> items = new HashMap<>();

    public <T, R> void put(Function<T, R> name, R value) {
        items.put(name, value);
    }

    public <T, R> R get(Function<T, R> name) {
        return (R)items.get(name);
    }
}

Solution

  • Your code contains two iF::apply Method Reference Expressions. Each time it creates a new Function<String, Integer> instance.

    Since those instances don't override equals() and hashCode() they are not really usable as keys in a HashMap. If you want to retrieve the entry that is already in the map you must use the same instance.

    That these are different instances can be seen from your screenshot:

    These names in the debug view are built using the simple classname (App$lambda) followed by @ followed by some unique identifier per object that the debugger encountered.