Junior — Middle
Have you used functional interfaces in Java in your projects?
sobes.tech AI
Answer from AI
Yes, in my projects I have used functional interfaces in Java, especially after the introduction of lambda expressions in Java 8. Functional interfaces are interfaces with a single abstract method, which allow the use of lambdas and method references for more concise and expressive code.
Examples of usage:
- Passing behavior to methods — for example, using
Predicate<T>,Function<T,R>,Consumer<T>for filtering, transforming, and processing collections. - Event handling and callbacks — simplifying code with lambdas.
- Parallel data processing with Stream API — where functional interfaces form the basis.
Example of using Predicate for filtering a list:
import java.util.*;
import java.util.function.Predicate;
public class Example {
public static void main(String[] args) {
List<String> names = Arrays.asList("Anna", "Bob", "Alice", "Mike");
Predicate<String> startsWithA = s -> s.startsWith("A");
names.stream()
.filter(startsWithA)
.forEach(System.out::println); // Will print Anna and Alice
}
}
Using functional interfaces allows writing more declarative and concise code.