Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use reference method in a UnaryOperator java 8

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.

like image 838
Dang Nguyen Avatar asked Jun 27 '26 04:06

Dang Nguyen


1 Answers

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;
like image 91
Misha Avatar answered Jun 29 '26 18:06

Misha