Senior
What is a lambda expression and a functional interface?
sobes.tech AI
Answer from AI
Lambda expression is a concise way of writing anonymous functions, allowing you to define a function directly at the point of use without needing to create a separate class or method. In Java, lambda expressions appeared in version 8 and enable writing more compact and expressive code.
Example of a lambda expression in Java:
Runnable r = () -> System.out.println("Hello, world!");
r.run();
Functional interface is an interface that contains exactly one abstract method. Such interfaces can be used as types for lambda expressions.
Example of a functional interface:
@FunctionalInterface
public interface Converter<F, T> {
T convert(F from);
}
Using with a lambda expression:
Converter<String, Integer> stringToInt = (String s) -> Integer.parseInt(s);
int number = stringToInt.convert("123");
Thus, lambda expressions allow for implementing functional interfaces in a concise and convenient manner, improving readability and reducing boilerplate code.