10 Things Java Developer Should Know about Lambda Expression of Java 8

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 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 might have questions like 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 the 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 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 to 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) The very first point about lambda expression is that 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 the 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 the right-hand side can be viewed as a 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 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 which accepts two String arguments and returns int by comparing their length like 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. 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.




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) -> {

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) 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;
}

}

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 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 the 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.



Btw, you would need Pluralsight membership to access this course which cost around $29 per month or $299 per year, which may seem big expensive at first but its completely worth of your money. You will get access to more than 5000 online courses on latest technology which will help you to learn anything you want.

I had bought Pluralsight membership on just $199 on one of their flash sales and strongly encourage all programmers to have that kind of membership, it helps you to keep up-to-date.

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) 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 like Predicate, Consumer etc.


9) Lambda expression is an 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.


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 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 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.


Further Learning
The Complete Java MasterClass
Java SE 8 for Really Impatient
From Collections to Streams in Java 8 Using Lambda Expressions


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:
  • 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)
  • Collection of best Java 8 tutorials (click here)
  • How to use debug Stream in Java 8 (tutorial)
  • Difference between abstract class and interface in Java 8? (answer)
  • Difference between Stream.map() and Stream.flatMap() in Java 8? (answer)
  • How to sort the may by values in Java 8? (example)
  • 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 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