10 points about lambda expressions in Java 8

The Lambda expression is one of the important features of Java 8 but if you look from a developer's point of view, it is nothing but a way to pass 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 e.g. 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 question, why lambda expression was introduced in the first place? Is it just the replacement of Anonymous class? Well, the lambda expression is more than that because it also introduces functional programming in Java.

Now, Java has best of both world i.e. 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 explain some important points about key concepts in Java. In earlier tutorials, you have learned about final modifierstatic modifierthreadenumeration typeheap memoryvolatile modifierinstanceof operator, and wait-notify methods. Those articles contain very good notes about corresponding Java concepts and you refer to them to refresh your knowledge.

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 lambda expression feature of Java 8.

10 Things about Lambda Expression of Java 8

1) You can pass a lambda expression to a method which accepts a functional interface i.e. a method which is either annotated by @Functional annotation e.g. interfaces from java.util.function package, or an interface with single abstract method e.g. Comparable, Comparator, Runnable, Callable, ActionListener etc.

2) 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 Strategy design pattern in Java.

3) Lambda expression is like anonymous function i.e. it defines parameter 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 right-hand side can be viewed as function body

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

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

The 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 which accepts two String arguments and returns an int by comparing their length e.g. positive if the length of first String is greater than second String, negative if first String's length is less than second String, and zero if both String has equal length.

4) 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) Even though lambda looks good with fewer lines of code, you can still write more than one lines of code in lambda by using curly braces as shown below:

(String first, String second) -> {

    return true;
    return false;

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

6) When you write conditional expressions in lambda e.g. if statements, make sure you return for every case, otherwise compilers will throw error, as shown in the following example

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

if( a > b){
   return 1;


Above code will not compile because you are only returning 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) Lambda expression in Java is of SAM type i.e. Single abstract method, which means you can pass a lambda expression to a method which expects an object of a class with exactly one abstract method. For example, 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 lambda expression to it

One more example is 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 lambda expression, I suggest you to take the course What's New in Java 8, you will not only learn about lambdas but other useful features of Java 8 as well.

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

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

lambda expression and anonymous class java 8

10) You can use a static, non-static, and local variable inside 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) You can also replace 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)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.

10 points about lambda expressions in Java 8

That's all about some of the important points about lambda expression in Java 8. It is one of the must know concept for Java developer 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 lazy evaluation feature of the stream and reduced boiler code of lambda expression. If you haven't yet started with Java 8, 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.

Further Reading
What's New in Java 8
The Ultimate Java 8 Tutorial
Java SE 8 New Features

Related Java 8 Tutorials
If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • How to join String in Java 8 (example)
  • How to use filter() method in Java 8 (tutorial)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to use Stream class in Java 8 (tutorial)
  • How to use forEach() method in Java 8 (example)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to convert List to Map in Java 8 (solution)
  • How to use peek() method in Java 8 (example)

Thanks a lot for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or suggestion then please drop a comment and I'll try to find an answer for you. 

No comments:

Post a Comment