Posted Dev / Java3 minutes read (About 518 words) visits
Functional Interface
SAM Interface
Single Abstract Method Interfaces (SAM Interfaces) are also known as Functional Interfaces.A functional interface in Java is an interface that contains only one abstract method. They can have any number of default or static methods.
The main roles of functional interfaces are:
Support for Lambda Expressions and Method References
Support for Stream API
Here’s an example of a functional interface which is implemented using a lambda expression:
// Method References /** * In this example, System.out::println is a method reference that refers to the println method of the System.out object. * The method reference is equivalent to the lambda expression x -> System.out.println(x). * Here this reference acts as Consumer functional interface instance. * void java.lang.Iterable.forEach(Consumer<? super String> action) */ publicclassMain() { publicstaticvoidmain(String[] args) { List<String> list = Arrays.asList("Apple", "Banana", "Cherry"); list.forEach(System.out::println); } }
@FunctionalInterface interfacePersonFactory { Person create(String name); }
PersonFactoryfactory= Person::new; Personperson= factory.create("John"); System.out.println(person.getName()); // Outputs: John
Examples of SAM Interfaces
Java’s standard library includes many commonly used SAM interfaces, such as Runnable, Callable, Comparable,Consumer, and many others in the java.util.function package.
@FunctionalInterface publicinterfaceCallable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call()throws Exception; }