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,

(parameters) OR () ->  {body with statements separated by;} OR Single Statement

Below are couple of examples,

() -> System.out.println("Back To Bazics.....!!!!!")    //Expression Prints "Back To Bazics.....!!!!!"
x -> System.out.println("The Value of X is : " + x)     //Expression Prints value of X 
(String name) -> System.out.println("Hello " + name)    //Expression Prints Greeting 
(int r) -> 2 * Math.PI * r                              //Expression for finding area of circle 
(double x, double y) ->  Math.pow(x,y)                  //Expression for finding x power of y
(a, b) -> a + b                                         //Expression for adding values of a and b

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

//Earlier
Thread t = new Thread(new Runnable(){
 public void run(){
  System.out.println("Back To Bazics.....!!!!!");
 }
}); 
t.run();

//With Lambda 
Runnable noArgsLambdaRef = () -> System.out.println("Back To Bazics.....!!!!!");
Thread t = new Thread(noArgsLambdaRef); 
t.run();

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

Implementation of ActionListener

JButton btn = new JButton();

//Earlier Implementation
ActionListener oneArgLambdaRef = new ActionListener({
    public void actionPerformed(ActionEvent event){
        System.out.println("button clicked")
    }
});

//Implementation With Lambda
ActionListener oneArgLambdaRef = event -> System.out.println("button clicked");

btn.addActionListener(oneArgLambdaRef);
btn.doClick();

Implementation of Comparator

class Car{
 public Car(String name, String model){
  this.name = name;
  this.model = model;
 }

 private String name;
 private String model;
 
 //Getter and Setter Methods
}

List cars = new ArrayList();
cars.add(new Car("BMW" , "X5"));
cars.add(new Car("BMW" , "X3"));
cars.add(new Car("Audi" , "R8"));
cars.add(new Car("Audi" , "Q7"));

//Earlier Implementation of Comparator
Collections.sort(cars, new Comparator() {
 public int compare(Car c1, Car c2) {
  return c1.getName().compareTo(c2.getName()) + c1.getModel().compareTo(c2.getModel()); 
 }
});

//Implementation of Comparator with Lambda
Comparator<Car> twoArgsLambdaRef = (c1, c2)  -> c1.getName().compareTo(c2.getName()) + c1.getModel().compareTo(c2.getModel()); 
Collections.sort(cars, twoArgsLambdaRef); 

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

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>