Java 8 Method References
30 Mar 2015The following is a fairly reasonable block of code that one might find in a project using Guava.
It's fairly hard to tell just from glancing at this code what it is actually doing. First it's transforming a group of Objects into different Objects, then it's filtering them based on the result of some predicate and then taking the first 5 results. Finally it forces the Iterables.doSomething()s to be evaluated by copying the result into an ImmutableList.
The main problem for this code's readability is those pesky anonymous classes for the Predicate
Lambdas and Stream can help things...
So that's turned 10 lines of code into 5. However s -> changeThing(s)
this still feels like it could be less verbose, doesn't it? Stream.map() and filter() expects a Function
Method References
Rather than telling the Stream how to use the method, we simply say there exists a method in this class called changeThing and testThing, go use them.
Some more examples...
This is useful because it means we don't need to create an anonymous class just to invoke an existing method, we can simply reference it to use it as a lambda expression. In cases where you are using an existing project with Guava that has been upgraded to use Java 8 and you don't want to mix Iterables and Stream this lets you take advantage of method references to make the code a little less verbose.
Originally posted on MetaBroadcast's blog.