Lambda

Functional interface and Marker interface were close friends and one day night they were walking through a forest. They were scared as they knew the fact that anything dangerous can happen to them at any time in the forest.  Suddenly they saw a bear approaching them. Marker interface tried to pull the gun from his pocket but unfortunately he didn’t have one in his pocket. Then Functional interface pulled the gun from his pocket and tried to shoot at the bear, but immediately he realized the fact that there are no bullets in the gun.

[If you were not able to laugh by reading the above joke(I call it as a joke), you need to undergo a small treatment of reading what is Functional interface and Marker interface. I don’t consider the default methods in Functional interface as guns 😆]

Lambda is an interesting feature which is added in Java SE 8. In collections it helps to iterate and get the data. Lambda expression is used to provide implementation for functional interfaces. An interface which has only one abstract method is called functional interfaces. @FunctionalInterface can be used to annotate an interface as functional interface. Lambda expressions are used for providing implementation for the Functional interface. Yes may think as an advanced version of anonymous class. Less coding and improved readability are the advantages of lambda.

The syntax for Lambda is:

 

argument(s)  -> method body

 

So let’s take a classic example of Comparator interface. Comparator interface is treated as a Functional interface since Java 8 as it has only one abstract method i.e. compare() which takes two arguments.

Student.java

==========

It’s a simple POJO, no explanation required.

public class Student {

private int id;

private String name;

private int mark;

 

public Student() {

}

 

public Student(int id, String name, int mark) {

super();

this.id = id;

this.name = name;

this.mark = mark;

}

 

public int getId() {

return id;

}

 

public void setId(int id) {

this.id = id;

}

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

public int getMark() {

return mark;

}

 

public void setMark(int mark) {

this.mark = mark;

}

 

@Override

public String toString() {

return “Student [id=” + id + “, name=” + name + “, mark=” + mark + “]”;

}

 

 

}

 

 

CompTest.java

============

It is a class where I create few Student objects, adding those to a List, then sorting using a Comparator and finally printing the objects.

 

import java.util.ArrayList;

 

public class CompTest {

 

public static void main(String[] args) {

// I have an ArrayList of Students.

ArrayList<Student> studentList = new ArrayList<Student>();

 

//Adding three student objects.

studentList.add(new Student(1, “Mark”, 89));

studentList.add(new Student(2, “John”, 78));

studentList.add(new Student(3, “Peter”, 96));

 

//Sorting the student objects in the ascending order of names. Used Lambda.

studentList.sort((studentOne,studentTwo) -> studentOne.getName().compareTo(studentTwo.getName()));

 

//Listing the student objects. Already overridden toString() in Student class. . Used Lambda.

studentList.forEach((student) -> System.out.println(student));

}

}

 

Key points:

  • I haven’t used sort() method of Collections utility class for sorting, instead used the sort() method of List interface which is added in Java 8.
  • sort() method takes an instance of Comparator interface implementation.
  • Within the sort method Lambda is used.
  • argument(s) is (studentOne,studentTwo)
  • method body is studentOne.getName().compareTo(studentTwo.getName())
  • An arrow mark is used in between the argument(s) and method body.
  • For fetching the objects in the list I used the forEach() method of Iterable interface.
  • forEach() method takes instance of a Consumer implementation and lambda is used for the implementation of accept() method of Consumer.

That’s all about Lambda. Now you can try with your own example; you may write your own Functional interface and give implementation for the abstract method using Lambda.

 

Saju Pappachen

 

About the author: Saju Pappachen is the Chief Consultant of jThread IT Training & Consultancy. He has more than 20 years of experience in Java technology. He is a Believer, Speaker, Dedicated to Inspiring & Transforming Lives to Greatness & Beyond.

He can be reached at saju@jthread.com

11 thoughts on “Lambda

  • Simple words put together explaining a really big picture. Simplification of a complex topic explains the depth of knowledge that the person has. Superb , Saju sir!

  • A great teacher and great programmer can explain complicated concepts in a student understandable language.So you are both sir.THANK YOU SIR FOR THIS GREAT INFORMATION.

  • Great explanation sir. In fact I was trying to understand lambda by reading some sites, but couldn’t follow it. But now I understood it. Thank you so much sir.

    Sir could you please give a sample code on how we write functional interface and implement it using lambda ?

  • sir,this valuable information never can be find by simply searching in various tutorials on internet and they are also very difficult to understand.But,this example is very well explained and simple.

Leave a Reply

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