Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this JAVA 8 lambda method work?

This is Java 8 lambda method what is its JAVA 7 equivalent?

public interface Function<T, R> {

    static <T> Function<T, T> identity() {
        return t -> t;
    }

    R apply(T t);
}

so its simply a JAVA interface but how t -> t is used ?

like image 381
Pradeep Kumar Kushwaha Avatar asked Aug 14 '26 22:08

Pradeep Kumar Kushwaha


1 Answers

That lambda expression is equivalent to the following anonymous class instance:

<T> Function<T, T> identity() {
    return new Function<T, T> () {
        public T apply (T t) {
            return t;
        }
    };
}

The lambda expression saves you the need to specify the name of the interface method you are implementing and its argument types, since they are only used to implement functional interfaces, which can have just one abstract method, so by stating the target interface type (Function<T, T> in this example), it's clear which method you are implementing.

Of course, Java 7 has no static interface methods, so you wouldn't be able to include that method inside an interface.

like image 119
Eran Avatar answered Aug 17 '26 06:08

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!