Advanced
Java Program to Demonstrate Lambda Expressions
A Java program to demonstrate the usage of Lambda Expressions.
Problem Description
Write a Java program to demonstrate the usage of Lambda Expressions (introduced in Java 8).
Code
interface MyInterface {
double getPiValue();
}
public class LambdaExample {
public static void main(String[] args) {
// declare a reference to MyInterface
MyInterface ref;
// lambda expression
ref = () -> 3.1415;
System.out.println("Value of Pi = " + ref.getPiValue());
}
}Output
Value of Pi = 3.1415Explanation
- Lambda Expression: A concise way to represent an anonymous function that can be passed around.
- Syntax:
(parameters) -> expressionor(parameters) -> { statements; }. - Functional Interface: An interface with only one abstract method.
