Java 8 – method references

Remember, lambda expressions are anonymous methods and they remove a lot of ceremonial code around the main instruction that the code is conveying.

Now consider the case where a lambda expression is simply calling a method that already exists, and nothing more. In that case, we can simply things even further.

If, say, you have a class SomeClass that has a method someMethod(int a, int b) then the lambda expression

(a, b) -> SomeClass.someMethod(a, b)

can be written using a method reference as just


Again, don’t confuse unfamiliar with more complicated. With practice you’ll see when lambda expressions and method references get the point of your code across better than the old way of doing things would.

There’s a little bit more to it, though. There are 4 different usages of method references.

Kind Example
Reference to a static method ContainingClass::staticMethodName
Reference to an instance method of a particular object containingObject::instanceMethodName
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName
Reference to a constructor ClassName::new

If you’d like to see more examples of method references check out the official docs here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s