How to use reference methods in unaryoperator Java 8

At present, I have an unaryoperator like this

UnaryOperator<Object> defaultParser = obj -> obj;

I don't know if method references can be used in these operations Example:

UnaryOperator<String> defaultParser = String::toString;

But the common way is not just string

Solution

If you only want to avoid lambda expressions, unaryoperator has a static identity () method:

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

If you specifically need a method reference (why?), Methods can be defined in the class

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

You will then be able to use it as a method reference:

UnaryOperator<Object> defaultParser = MyClass::identity;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>