How can I use reference method in a UnaryOperator java 8

Dang Nguyen :

Currently, I have a UnaryOperator like this

UnaryOperator<Object> defaultParser = obj -> obj;

I don't know if I can use a method reference in these kinds of operation. Example:

UnaryOperator<String> defaultParser = String::toString;

But with the generic way, not just String.

Misha :

If you just want to avoid the lambda expression, UnaryOperator has static identity() method:

UnaryOperator<Object> defaultParser = UnaryOperator.identity();

If you specifically want a method reference (why??), you can define a method in your class

public static <T> T identity(T t) {
    return t;
}

Then you will be able to use it as a method reference:

UnaryOperator<Object> defaultParser = MyClass::identity;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88749&siteId=1