Java 8: Lambda Expressions

Java 8 is completing almost 2 years now and this topic is widely discussed on Internet now a days. Java was originally designed to work OOP as it was the primary paradigm for software development at that time. But today’s programming directed towards concurrent and reactive programming which focuses on functional modularity which is provided by functional languages like Scala.

Concept of functional programming is completely a new era for the hard core Java Programmers and lambda expressions are bridging OOP and FP by adding functional language capabilities to Java. You will find this concept roaming around anonymous classes and functional programming.

Before we move ahead I recommend you to brush up your understanding of functional programming basics.

What is Lambda Expressions in Java 8?

It is a nameless function (anonymous function) which can be passed to another function as a parameter. You can consider it as a piece of encapsulated functional code which can be passed around as a reference which will be executed afterwards.

Basically in all Object Oriented programming languages,

  • Objects and Classes are first class candidates, which means we can create references of objects and assign it to any of the variable of that class type
  • Functions doesn’t have the references, one cannot create reference of function similar to objects

While in Functional Programming,

  • Functions are treated as primary candidates and they can exist same was as objects in OOP
  • Functions can be assigned to any variable and can be passed to other functions as an argument

Lambda Expressions are functions which could be treated as those first class candidates which we have just discussed.

The Basic Structure of the Lambda Expression is as below,

Below are couple of examples,

After knowing about lambda, another question comes about the type (which can hold the references of such expressions). The answer is Functional Interfaces. In Java 8, an interface with one and only one abstract method is called Functional interface. @FunctionalInterface annotation is used in Java 8 for compile time validation of Functional Interfaces(it is not mandatory). You can find more about them in my another post Java 8 : Functional Interfaces

Let’s have most commonly used examples of the above concept.

Implementation of Runnable

You can see in above implementation, code with Lambda Expression is quite cleaner, readable and has just of two lines.

Implementation of ActionListener

Implementation of Comparator

Advantages of Java 8 Lambdas

  • Modular Functional design
  • Ability to pass methods as parameters and get methods as a return value from a function
  • Compact and clean code
  • Performance improvement due to laziness
  • Easy parallel execution with Streams

We’ll discuss more about Java 8 Lambda Expressions in detail with easy examples in my upcoming posts.

Stay Tuned & nJoy Learning…..!!!!!

Leave a Reply

Notify of