How to replace lambda expression with method reference in Java 8

If you are using a lambda expression as an anonymous function but not doing anything with the argument passed, you can replace lambda expression with method reference. Below code is good example to replace lambdas with method reference -> {

Since we are not modifying the number argument here, we can replace the lambda expression:

number -> { 

with method reference as shown below:;

but, if you modify the argument before passing it to another method then you cannot replace lambdas with method reference e.g. in the following case we cannot do that: -> {

The double colon (::) operator is used for method reference and there are actually three main cases to use it:


In first two cases, the method reference is equivalent to lambda expression that supplies the parameters of the method e.g. System.out::println is equivalent to x -> System.out.println(x) and Math::pow is equivalent to (x, y) -> Math.pow(x, y).

In this case, the first parameter becomes the target of the method. For example, String::compareToIgnoreCase is the same as

(x, y) -> x.compareToIgnoreCase(y)


this::equals is same as

(x -> this.equals(x))

You can read more about converting this type of lambda expression into method reference in Java SE 8 for Really Impatient, it has got little bit more explanation and examples on this topic.
Another good example of replacing lambda expression with method reference is the following code of sorting a map by values in Java 8:

Map sortByValue = map.entrySet()
.sorted(Map.Entry.<String, Integer>comparingByValue())
.collect(Collectors.toMap(e -> e.getKey(),e -> e.getValue()));

can be rewritten as following using method reference :

Map sortByValue = map.entrySet()
.sorted(Map.Entry.<String, Integer>comparingByValue())
               Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

if you look closely, we have replaced e -> e.getKey() with Map.Entry::getKey and e -> g.getValue() to Map.Entry::getValue because we already have code what those lambda expressions were doing in form of getKey() and getValue() method.

That’s all about when and how to replace lambda expression with method reference in Java 8. You can replace only if you are not doing any modification, otherwise, you cannot replace. Why you want to do that? Well, because method reference is more succinct and readable than lambda expression.
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at #techcodebit #google #microsoft #facebook #interview portal #jobplacements


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar