Search code examples
javalambdasyntaxjava-8functional-interface

Is it possible to abbreviate java functions removing the variable?


In Java 8’s functions, there is a shortcut for, i.e.

() -> new ArrayList()

which then reads:

ArrayList::new

When working with streams, I find myself declaring a lot of functions like this:

s.map(var -> var.getFoo()).flatMap(var -> var.parallelStream()).map(var -> var.getBar())

Is there also an abbreviation if the prefix is var -> var.? Something like

s.map(::getFoo()).flatMap(::parallelStream()).map(::getBar())

Solution

  • The syntax of method reference is defined at JLS-15 and written as Object::method without discussion - you can't write ::method since the origin of the method would remain unknown. The variable var is an instance of an object, right? Thus:

    s.map(MyObject::getFoo).flatMap(Collection::parallelStream).map(MyObject::getBar)
    

    My personal suggestion is to choose the readable way over the short way. Shortening doesn't imply readability. For some reason I don't like Object::method method reference and rather use var -> var.method(). This is a matter of discussion and personal preference.

    However, the statement above the code snippet is definitive. You have to follow the syntax.