×
☰ See All Chapters

Java Functional Interfaces

An interface with single abstract method is called as functional interface. An example is java.lang.Runnable. Java provides an annotation @FunctionalInterface, which is used to declare an interface as functional interface. @FunctionalInterface is not mandatory to make interface as functional interface, this is as if we use optional @Override annotation to methods to indicate that we are overriding a method. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces.

The interface does not have to be user defined. It can be any interface, defined in previous versions of JDK or of any third party library. It has to have only one method does not matter whatever the signature is or how many arguments it has or whether it returns a value or not.  

Java Lambda Expressions

Lambda expressions are new alternative to anonymous classes with an obvious benefit of avoiding boilerplate code. As for inner classes no new .java file will be created and as inner classes does not belongs to any class, lambda expressions can be created without belonging to any class. Lambda expressions express instances/object of functional interfaces. Lambda expression provides implementation of functional interface.

Lambda Expressions Syntax

(argument-list) -> {statements}

There are four important rules to the syntax:

  1. Declaring the types of the parameters is optional. 

  2. Using curly braces is optional (unless you need multiple statements). 

  3. When you have used curly braces, irrespective of number of statements, return keyword is mandatory. When you have not used curly braces, then it should be a single statement, it should have no return keyword and this statement should be evaluated to some value. 

  4. Using parentheses around the parameter is optional if you have only one parameter. 

Number of parameters

Parentheses around the parameter

0

Required

1

Optional

Greater than 1

Required

Lambda Expressions Examples

Without Lambda Expression

package com.java4coding;

 

interface PrintHello {

        public void print();

}

 

public class LambdaExpressionDemo {

 

        public static void main(String[] args) {

 

                PrintHello printHello = new PrintHello() {

 

                        @Override

                        public void print() {

                                System.out.println("Hello");

                        }

                };

        }

printHello.print();

}

With Lambda Expression

package com.java4coding;

 

interface PrintHello {

        public void print();

}

 

public class LambdaExpressionDemo {

 

        public static void main(String[] args) {

                PrintHello printHello = () -> {System.out.println("Hello");};

                printHello.print();

        }

}

 “return” keyword in Lambda Expression

java-lambda-expressions-0
 
java-lambda-expressions-1
 

package com.java4coding;

 

interface Employee {

        public String getFullName(String firstName, String lastName);

}

 

public class LambdaExpressionDemo {

 

        public static void main(String[] args) {

                Employee employee1 = (String firstName, String lastName) ->  firstName.concat(" ").concat(lastName);

                Employee employee2 = (String firstName, String lastName) ->  firstName + " " + lastName;

                //Employee employee4 = (String firstName, String lastName) ->  return firstName + " " + lastName; // return keyword is not allowed without curly braces

                //Employee employee3 = (String firstName, String lastName) ->  {firstName.concat(" ").concat(lastName);}; //return keyword is required.

                String fullName = employee1.getFullName("Manu", "Manjunatha");

                System.out.println(fullName);

        }

}

Lambda Expression Example: To implement Comparator

package com.java4coding;

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

 

class Employee {

 

        private int id;

        private String name;

 

        public Employee(int id, String name) {

                this.id = id;

                this.name = name;

        }

 

        // Getters & Setters

        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 class LambdaExpressionDemo {

 

        public static void main(String[] args) {

 

                List<Employee> list = new ArrayList<>();

                list.add(new Employee(123, "Manu Manjunatha"));

                list.add(new Employee(123, "Advith Tyagraj"));

               

                Collections.sort(list, (Employee e1, Employee e2) -> e1.getName().compareTo(e2.getName()));

 

                for(Employee emp: list) {

                        System.out.println(emp.getName());

                }

        }

}

 

In the above example observe carefully, in the lambda expression we have not ended the statement by semicolon (;), here the sort method expects the second argument of type Comparator, we have to pass the Comparator object. Consider the below method:

public void setEmployee(Employee emp) {

}

To call the above method below is the syntax

obj.setEmployee(new Employee());

Below statement will give syntax error:

obj.setEmployee(new Employee(););

Following this, I hope you now got the idea why we have not used semicolon (;) in the end of lambda expression;

Below code gives the different ways of coding lambda expression for comparator.

package com.java4coding;

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

 

class Employee {

 

        private int id;

        private String name;

 

        public Employee(int id, String name) {

                this.id = id;

                this.name = name;

        }

 

        // Getters & Setters

        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 class LambdaExpressionDemo {

 

        public static void main(String[] args) {

 

                List<Employee> list = new ArrayList<>();

                list.add(new Employee(123, "Manu Manjunatha"));

                list.add(new Employee(123, "Advith Tyagraj"));

               

                Comparator<Employee> empComparator1 =  (Employee e1, Employee e2) -> {return e1.getName().compareTo(e2.getName());};

                Collections.sort(list, empComparator1);

               

                Comparator<Employee> empComparator2 =  (Employee e1, Employee e2) ->  e1.getName().compareTo(e2.getName());

                Collections.sort(list, empComparator2);

               

                Collections.sort(list, (Employee e1, Employee e2) -> e1.getName().compareTo(e2.getName()));

               

                Collections.sort(list, (Employee e1, Employee e2) -> {return e1.getName().compareTo(e2.getName());});

               

                // Not possible, return keyword missing, when curly braces is used,return keyword is mandatory

                //Collections.sort(list, (Employee e1, Employee e2) -> { e1.getName().compareTo(e2.getName());});

               

                // Not possible, syntax error due to semicolon in the end of lambda expression

                //Collections.sort(list, (Employee e1, Employee e2) -> e1.getName().compareTo(e2.getName()););  

               

                // Not possible, syntax error due to semicolon in the end of lambda expression

                //Collections.sort(list, (Employee e1, Employee e2) -> {return e1.getName().compareTo(e2.getName());};);

               

                // Not possible, return keyword is not allowed without out curly braces

                //Collections.sort(list, (Employee e1, Employee e2) -> return e1.getName().compareTo(e2.getName()));  

               

                for(Employee emp: list) {

                        System.out.println(emp.getName());

                }

        }

}

 


All Chapters
Author