Functional Interfaces with Lambdas in Java


Write a Java program to demonstrate the use of a functional interface with lambdas and method references

  • Operation is a functional interface with a single abstract method perform.
  • The Main class contains a static method add(int a, int b) which simply adds two integers and returns the result.
  • A lambda expression is used to create an instance of Operation for addition.
  • A method reference Main::add is used to create an instance of Operation for subtraction, referring to the add method in the Main class.
  • The perform method of each instance of Operation is called with different arguments to demonstrate addition and subtraction operations.

Source Code

@FunctionalInterface
interface Operation
{
	int perform(int a, int b);
}
 
public class Main
{
	public static int add(int a, int b)
	{
		return a + b;
	}
 
	public static void main(String[] args)
	{
		Operation addition = (a, b) -> a + b;
		Operation subtraction = Main::add;
 
		System.out.println("Addition : " + addition.perform(4, 3));
		System.out.println("Subtraction : " + subtraction.perform(10, 7));
	}
}

Output

Addition : 7
Subtraction : 17

Example Programs