As you noted, the semantics of the lambda x -> x != null
and the method reference Objects::nonNull
are virtually identical. I'm hard-pressed to think of any actual observable difference, short of digging into the class using reflection, or something like that.
There is a small space advantage to using the method reference over the lambda. With the lambda, the code of the lambda is compiled into a private static method of the containing class, and the lambda metafactory is then called with a reference to this static method. In the method reference case, the method already exists in the java.util.Objects
class, so the lambda metafactory is call with a reference to the existing method. This results in a moderate space savings.
Consider these small classes:
class LM { // lambda
static Predicate<Object> a = x -> x != null;
}
class MR { // method reference
static Predicate<Object> a = Objects::nonNull;
}
(Interested readers should run javap -private -cp classes -c -v <class>
to view detailed differences between the way these are compiled.)
This results in 1,094 bytes for the lambda case and 989 bytes for the method reference case. (Javac 1.8.0_11.) This isn't a huge difference, but if your programs are likely to have large numbers of lambdas like this, you might consider the space savings resulting from using method references.
In addition, it is more likely that a method reference could be JIT-compiled and inlined than the lambda, since the method reference is probably used a lot more. This might result in a tiny performance improvement. It seems unlikely this would make a practical difference, though.
Although you specifically said "Other than code style..." this really is mostly about style. These small methods were specifically added to the APIs so that programmers could use names instead of inline lambdas. This often improves the understandability of the code. Another point is that a method reference often has explicit type information that can help out in difficult type inference cases, such as nested Comparators. (This doesn't really apply to Objects::nonNull
though.) Adding a cast or explicitly-typed lambda parameters adds a lot of clutter, so in these cases, method references are a clear win.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…