Skip to main content

Java 8 features - Functional Interface and Lambda Expression

Functional Interface in Java

Functional Interface is defined as an interface with only one abstract method.one of the example of Functional interface in java.lang package is Runnable with only one abstract method run().

we can use Annotation , @FunctionalInterface to create Functional interface in java , actually this annotation is not mandatory , but if we write this annotation , and in future if somebody try to add new abstract method in our interface then he will get Error as  : Invalid '@FunctionalInterface' annotation.

Functional Interfaces are also called as Single Abstract Method(SAM) interfaces.

Using Functional Interfaces,Anonymous Inner classes are implemented.

Example :

public class TestAnonymousInnerClass {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("Implementing Runnable");
			}
		}).start();
	}
}

Output :
Implementing Runnable

Lambda Expressions in java

Lambda Expression is used to implement Functional Interface , 
Syntax for lambda :
(parameters)->{statements};
Example :
1.(int a,int b) -> a+b;

2.(a,b) -> a-b;

3.() -> 12;

4.(String msg) -> System.out.println(msg);

5.(a,b) -> {
System.out.println("Addition is "+(a+b));
System.out.println("Subtraction is "+(a-b));
};

Example :

public class TestLambdaExpression {
	public static void main(String[] args) {
		Runnable r1 = () -> {
			System.out.println("Using Lambda Thread 1");
		};
		new Thread(r1).start();

		Thread t2 = new Thread(() -> {
			System.out.println("Using Lambda Thread 2");
		});
		t2.start();

		new Thread(() -> {
			System.out.println("Using Lambda Thread 3");
		}).start();
	}
}


Output :
Using Lambda Thread 1
Using Lambda Thread 2
Using Lambda Thread 3
Note - There can be N number of default and static method but only one abstract method in functional interface. 

Example of Functional Interface in java  :

@FunctionalInterface
interface StudentAction{
	void act(String s);
}

public class TestLambdaExpression {
	public static void main(String[] args) {
		StudentAction studentAction=(s)->System.out.println(s);

		studentAction.act("visit crtr4u.com");
		studentAction.act("learn code");
		studentAction.act("do pratice");
		studentAction.act("get job");	
	}
}

Output :
visit crtr4u.com
learn code
do pratice
get job
Here is one more example , using lambda expression , try to understand it and practice :

Example :Functional Interface in java :

Step 1: Write 4 functional interfaces as below :

@FunctionalInterface
interface AdditionInterface{
	int add(int a,int b);
}

@FunctionalInterface
interface SubtractionInterface{
	int subtract(int a,int b);
}

@FunctionalInterface
interface MultiplicationInterface{
	int multiply(int a,int b);
}

@FunctionalInterface
interface DivisionInterface{
	int divide(int a,int b);
}

Step 2: Write MyUtility class as below :

class MyUtility{
	void perform(Object obj,int num1,int num2){
		if(obj instanceof AdditionInterface){
			System.out.println("Addition is :"+((AdditionInterface)obj).add(num1, num2));
		}
		else if(obj instanceof SubtractionInterface){
			System.out.println("Subtraction is :"+((SubtractionInterface)obj).subtract(num1, num2));
		}
		else if(obj instanceof MultiplicationInterface){
			System.out.println("Multiplication is :"+((MultiplicationInterface)obj).multiply(num1, num2));
		}		
		else if(obj instanceof DivisionInterface){
			System.out.println("Division is :"+((DivisionInterface)obj).divide(num1, num2));
		}
		else {
			System.out.println("Action is Unknown");
		}
	}
}

Step 3: Write Main class as below and execute it :

public class TestLambdaExpression {
	public static void main(String[] args) {
		AdditionInterface add=(a,b)->a+b;		
		SubtractionInterface subtract=(a,b)->a-b;
		MultiplicationInterface multiply=(a,b)->a*b;
		DivisionInterface divide=(a,b)->a/b;
		
		MyUtility myUtility=new MyUtility();
		
		myUtility.perform(add, 9, 3);
		myUtility.perform(subtract, 9, 3);
		myUtility.perform(multiply, 9, 3);
		myUtility.perform(divide, 9, 3);
	}
	
}

Output :
Addition is :12
Subtraction is :6
Multiplication is :27
Division is :3
Understand above code and execute it , happy learning.

Popular Posts

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Today we will see solution for Error In Spring Boot : ***************************  APPLICATION FAILED TO START ***************************  Description: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.  Reason: Failed to determine a suitable driver class. --->My Application.yml : server: port: 8081 spring: datasource: driver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:xe username: sys as sysdba password: root Oracle Version is 21 C Oracle Database 21c Express Edition Release 21.0.0.0.0 - Production Version 21.3.0.0.0. check my pom.xml here : <? xml version = " 1.0 " encoding = " UTF-8 " ?> < project xmlns = " http://maven.apache.org/POM/4.0.0 " xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance " xsi:schemaLocation = " http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/m...

Stream In Java

stream in java 8 : Stream API is used to process collection of objects. stream() method is present in Collection interface from package java.util . Stream is an interface present in java.util package, filter() and map() methods are present in Stream interface. -->when to use filter()  method ? If we want to filter elements from collection based on some boolean condition then we can use filter() method.  for example  : filtering even or odd numbers from list of numbers. -->When to use map()  method ? If we want to create new object for every object in collection then we should use map() method. for example : if we want to increase every number in list by 2 , here every object is getting modified ,we have to use map() in this type of scenario. In below example , we used both filter() and map() methods on stream , inside filter method we applied some condition and in map method we are transforming our object to different one. package com.crtr4u.www; import java...

How much Software Engineer Earn in India

  No limit of earning for free lancer software developer : In service based companies - If Software Engineer work for same MNC from beginning of career then sometimes financial growth is low,still they can reach in between 7 lacs to 15 lacs in India. If programmer switch job after every 2-3 year and work for at least 5 years then they can earn minimum in between 14 lacs to 25 lacs for the position of Senior Software Engineer.  Being from a normal college , completed my education with average percentage , then  As 2 year experienced guy - I was getting offers of 8 lacs, 10 lacs  As 5 years experienced guy the offers are like  Minimum 12 lacs ,14 lacs, 18 lacs from Indian MNCs.  Money is  no bar for right candidate, if you are able to crack interview and if you can  write effective code then you can earn more than 20 lacs in India itself. Be motivated, improve your technical skills and yes you can earn great amount from Job too...  People with ...