简体   繁体   中英

Java 8, Static methods vs Functions

In Java 8 I want to create something that returns an argument or creates an instance if the argument is null.

I could do this by creating a static method or a UnaryOperator. Are the following approaches technically the same or are there technical differences that I should be aware of with either approach:

Static Method

static Cat initOrReturn(Cat c) {
    if (c==null) {
        return new Cat();
    }
    return c;
}

Function

UnaryOperator<Cat> initOrReturn = c -> {
    if (c==null) {
        return new Cat();
    }
    return c;
}

First your code has syntax error, in the second block first line between c and { there should be a -> .

The second one creates an anonynous object, the first one only creates a static method.
So they're not the same.

Also, static methods can be used in stream API.
If you have:

class A {
  static Object a(Object x) { return x; /* replace with your code */ }
}

You can:

xxxList().stream().map(A::a)

Creating a method is often considered dirty, because it's globally visible.
It's recommended to use lambda expressions without declaring a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM