capypad
0 Tage Serie
java / intermediate
Snippet

Funktionale Schnittstellen und Lambda-Ausdrücke

Funktionale Schnittstellen enthalten genau eine abstrakte Methode und können mittels Lambda-Ausdrücken implementiert werden, um eine prägnante Darstellung anonymer Funktionen zu ermöglichen.

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));
}
}
Erklärung
1
@FunctionalInterface
Eine Annotation, die sicherstellt, dass das Interface nur eine abstrakte Methode besitzt.
2
(a, b) -> a + b
Ein Lambda-Ausdruck, der die 'operate'-Methode ohne formale Klassendeklaration implementiert.