capypad
0 day streak
java / intermediate
Snippet

Functional Interfaces and Lambda Expressions

Functional interfaces contain exactly one abstract method and can be implemented using lambda expressions to provide a concise way to represent anonymous functions.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
 
public class LambdaExample {
public static void main(String[] args) {
MathOperation addition = (a, b) -> a + b;
System.out.println("Result: " + addition.operate(10, 5));
}
}
Breakdown
1
@FunctionalInterface
An annotation ensuring the interface has only one abstract method.
2
(a, b) -> a + b
A lambda expression that implements the 'operate' method without a formal class declaration.