Functional Interfaces | Java
A functional interface is an interface that contains only one abstract method.
From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
Functional interfaces are used and executed by representing the interface with an annotation called @FunctionalInterface.
Some Built-in Java Functional Interfaces
Since Java SE 1.8 onwards, there are many interfaces that are converted into functional interface. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows –
- Runnable –> This interface only contains the run() method.
- Comparable –> This interface only contains the compareTo() method.
- ActionListener –> This interface only contains the actionPerformed() method.
- Callable –> This interface only contains the call() method.
Java SE 8 included four main kinds of functional interfaces which can be applied in multiple situations. These are:
- Consumer
- Predicate
- Function
- Supplier
Examples:
- ) Predicate
Example-1
List<String> names = Arrays.asList(“Angela”, “Aaron”, “Bob”, “Claire”, “David”);
List<String> namesWithA = names.stream() .filter(name -> name.startsWith(“A”)) .collect(Collectors.toList());
Example-2
Consumer<String> print = x -> System.out.println(x);
print.accept("java"); // java