Why is Predicate.isEqual implemented as it is?

Recently, I have been messing around with new java8 features to better understand them.

When trying to use some elements with, Stream.filterI came across a source Predicate.javain which I found the following implementation of the method isEqual:

/**
 * Returns a predicate that tests if two arguments are equal according
 * to {@link Objects#equals(Object, Object)}.
 *
 * @param <T> the type of arguments to the predicate
 * @param targetRef the object reference with which to compare for equality,
 *               which may be {@code null}
 * @return a predicate that tests if two arguments are equal according
 * to {@link Objects#equals(Object, Object)}
 */
static <T> Predicate<T> isEqual(Object targetRef) {
    return (null == targetRef)
            ? Objects::isNull
            : object -> targetRef.equals(object);
}

What it made me wonder whether this line: : object -> targetRef.equals(object);.

Maybe I overdid it a lot, but I could not immediately think why this line was not : targetRef::equals;like this:

static <T> Predicate<T> isEqual(Object targetRef) {
    return (null == targetRef)
            ? Objects::isNull
            : targetRef::equals;
}

It seems to me that unnecessarily creating a lambda otherwise.

If I didn’t miss something, I don’t care. (Is this the same?) Is there a reason why the current implementation is chosen? Or is it just incredibly small that they just missed it or no one cared.

, : - ? - (, ) ?

+4
1

?

, , , , → , , . , .

, , , , .


, ( )

, : - ? - (, ) ?

, . , 9.

import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        Consumer<String> lambda = s-> printStackTrace(s);
        lambda.accept("Defined as a lambda");

        Consumer<String> methodRef = Main::printStackTrace;
        methodRef.accept("Defined as a method reference");
    }


    static void printStackTrace(String description) {
        new Throwable(description).printStackTrace();
    }
}

java.lang.Throwable: Defined as a lambda
    at Main.printStackTrace(Main.java:15)
    at Main.lambda$main$0(Main.java:6)
    at Main.main(Main.java:7)

java.lang.Throwable: Defined as a method reference
    at Main.printStackTrace(Main.java:15)
    at Main.main(Main.java:10)

Main.lambda$main$0, , printStackTrace

, , ( ) . .

.

Consumer<String> print1 = System.out::println; // creates an object each time
Consumer<String> print2 = s->System.out.println(s); // creates an object once.

, System.setOut, , PrintStream .

+7

Source: https://habr.com/ru/post/1657262/


All Articles