Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 462
Andy Cribbens Avatar asked Aug 01 '26 23:08

Andy Cribbens


1 Answers

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.

like image 104
ice1000 Avatar answered Aug 03 '26 12:08

ice1000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!