How to use Lambda Expression and method reference in Java? Example Tutorial

Hello guys, if you are wondering what is lambda expression and method reference in Java then you are at the right place. Earlier, I have shared 10 Stream API examples and in this article, I will share everything I know about Lambda expression with you. The Lambda expression is one of the most important features of Java 8 which has opened a whole new dimension of programming paradigm in Java. It is the feature which made the Functional Programming possible in Java because now you can pass the code to a function to execute as opposed to an object. You might be a bit surprised but if you look from a developer's point of view, it is nothing but a way to pass your code to a method in Java.

Technically, it's an expression where you can define parameters and then the code which uses those parameters, similar to a method in Java, but you don't need to write boilerplate code like method name, return type, argument type, etc. Most of those details are inferred by compiler and JVM from the context in which lambda expression is used.

Some of you might have questions like why lambda expression was introduced in the first place? Is it just the replacement of the Anonymous class? Well, the lambda expression is more than that because it also introduces functional programming in Java.

Now, Java has the best of both worlds, I mean Object-oriented programming and Functional programming which means you can write even more scalable and robust, mission-critical application in Java.

This is another article of my 10 points series, where I like to explain some important points about key concepts in Java. In earlier tutorials, you have learned about
  1. final modifier
  2. static modifier
  3. thread
  4. enumeration type
  5. heap memory
  6. volatile modifier
  7. instanceof operator
  8. and wait-notify methods.

Those articles contain very good notes about corresponding Java concepts and you refer to them to refresh your knowledge.

Btw, if you are new to Java and just starting to learn Java Programming from JDK 8 onwards, I suggest you first take a look at a comprehensive Java Course like The Complete Java Masterclass on Udemy. It's one of the best and also most up-to-date, recently updated for the latest Java version.





10 Things about Lambda Expression of Java 8

Today I'll share 10 useful points about lambda expressions in Java 8. These points will give you a basic idea of lambda expression and encourage you to learn more about it.

These are also a good refresher for Java Interviews and Java 8 certifications. It's kind of my personal notes about the lambda expression feature of Java 8.


1. You can pass a lambda expression as a method argument

The very first point about lambda expression is that you can pass a lambda expression to a method that accepts a functional interface i.e. a method that is either annotated by @Functional annotation e.g. interfaces from java.util.function package, or an interface with a single abstract method e.g. Comparable, Comparator, Runnable, Callable, ActionListener, etc.


2. Lambda provides a way to pass dynamic code

The lambda expression allows you to pass a custom code to your Java method, which was not possible earlier. The only option you had was to work around your way by wrapping the code as an object and passing it to a method using anonymous classes. Also known as the Strategy design pattern in Java.



3.  Anonymous Function

Lambda expression is like an anonymous function i.e. it defines parameters and code which operates on those parameters, but you can pass this anonymous function to any method just like you pass an object. The left-hand side of lambdas can be viewed as parameters while the right-hand side can be viewed as a function of body

e.g. (int a, int b) -> a + b

is a method that accepts two integers arguments a and b and returns the sum of them. The return keyword is not required if lambda expression is a one-liner.

Another example of one linear lambda expression is:

(String first, String last) -> Integer.compare(first.length(), last.length());

you can view this as a function that accepts two String arguments and returns int by comparing their length like positive if the length of the first string is greater than the second String, negative if the first String's length is less than the second String, and zero if both String has equal length. 

You can further see From Collections to Streams in Java 8 Using Lambda Expressions course on Pluralsight to learn more about how to use a lambda expression in your day-to-day coding.


best course to learn lambda expression



4.  Parameters are not mandatory

It's not mandatory for a lambda expression to have parameters, you can write a lambda expression without parameters as shown below:

() -> System.out.println("lambda without parameter");


5.  Lambda Block

Even though lambda looks good with fewer lines of code, you can still write more than one line of code in lambda by using curly braces as shown below:

(String first, String second) -> {

if(first.equals(second)){
    return true;
}else{
    return false;
}
};

Though in this case, the return keyword is mandatory, you cannot omit it like a single line of lambda code.



6. You can return value from Lambda expression

When you write conditional expressions in lambdas like if statements, make sure you return for every case, otherwise compilers will throw an error, as shown in the following example

// bad - compile time error
(Integer a, Integer b) - {

if( a > b){
   return 1;
}

}

The above code will not compile because you are only returning the value in case if the condition is true. You should also return to the else condition as shown below:

// good - returning in all cases
(int a, int b) - {
if(a > b){
  return 1;
}else if ( a < b){
  return -1;
} else {
  return 0;
}

};


7. SAM Type

Lambda expression in Java is of SAM type like Single abstract method, which means you can pass a lambda expression to a method that expects an object of a class with exactly one abstract method. For example, the Executor.submit() method accepts a Runnable, which has just one method so you can pass it a lambda expression as follows:

Another example is Collections.sort() which accepts a Comparator, another interface with just one abstract method compare(), you can pass a lambda expression to it

One more example is the addListener() method which acceptions an EventListener, you can pass a lambda to it because ActionListener just has one abstract method, actionPerformed(). 

If you want to learn more about where you can use a lambda expression, I suggest you take a course like What's New in Java 8 on Pluralsight you will not only learn about lambdas but other useful features of Java 8 as well.

How to use Lambda Expression and method reference in Java? Example Tutorial

Anyway, even if you don't have Pluralsight membership you can still access this course by taking their 10-day FREE Pass which allows 200 minutes of free access to all their courses. That is enough time to access this course.


8. Functional Interface

You can also pass a lambda expression to methods that accept a Functional interface, introduced in Java 8. These are interface annotated with @Functional annotation and contain just one abstract method. Java 8 API comes with several in-built functional interfaces in package java.util.function like Predicate, Consumer, etc.



9. Alternative of Anonymous class

Lambda expression is an alternative to an anonymous class in Java and should be able to replace all its uses where the Anonymous class implements an interface or extend a class with just one abstract method. See Java SE 8 for Really Impatient to learn more about how to replace the Anonymous class with lambda expression in Java 8.

lambda expression and anonymous class java 8



10. Types of variables inside the lambda expression

You can use a static, non-static, and local variable inside a lambda expression, this is called capturing variables inside the lambda. By the way, only final or effectively final local variables are allowed inside lambda expressions.


11. Method Reference

You can also replace the lambda expression with the method reference if a method is not modifying the parameter supplied by the lambda expression. For example following lambda expression can be replaced with a method reference since it is just a single method call with the same parameter:




12. Serialization of Lambda expression

You can serialize a lambda expression if its target type and its captured arguments are serializable. However, like inner classes, the serialization of lambda expressions is strongly discouraged. You can read more about it on Java 8 in Action, one of the best books to learn Java 8.


That's all about some of the important points about lambda expression in Java 8. It is one of the must-know concepts for Java developers because it has totally changed the way you code in Java.

The key benefit of Lambda expression is that it allows you to pass a block of code to a method in Java. Earlier it wasn't possible because you can only pass objects to Java methods, you cannot pass a function to them, but lambda expression now allows you to pass a block of code, just like an anonymous function of JavaScript.

Several tried and tested idioms are now rewritten using lambda expression and stream to take advantage of the lazy evaluation feature of the stream and reduced boiler code of lambda expression.

 If you haven't yet started with Java 8 yet, then now is the time to learn Java 8 because very soon every company will start hiring Java Developers with good command in Java 8.



Related Java 8 Tutorials
If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • 5 Free Courses to learn Java 8 and 9 (courses)
  • 5 Books to Learn Java 8 Better? (read here)
  • 10 Examples of converting a List to Map in Java 8 (see here)
  • Java 8 Comparator Example (check here)
  • 10 Advanced Core Java courses for Programmers (courses)
  • Collection of best Java 8 tutorials (click here)
  • Best Courses to learn Java Programming for Beginners (best courses)
  • How to use debug Stream in Java 8 (tutorial)
  • Difference between abstract class and interface in Java 8? (answer)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • Difference between Stream.map() and Stream.flatMap() in Java 8? (answer)
  • How to sort the may by values in Java 8? (example)
  • 7 best Courses to learn Data structure and Algorithms (best online courses)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • Top 5 Course to master Java 8 Programming (courses)
Thanks for reading this article so far. If you like this Java 8 filter method tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S.- If you just want to learn more about new features in Java 8 then you can also see this list of Free Java 8 Courses on FreeCodeCamp. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API, and other miscellaneous changes.

3 comments:

  1. Just fyi, some of the examples have been lost from the text above.

    ReplyDelete
  2. Can someone tell me why do we need collect method in java 8.I know its uses but how should it be answered in an interview..

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.