Functional Interfaces - RichardDanielOliva/java-learning-wiki GitHub Wiki
Lambda expressions go hand in hand with functional interfaces, the concept of functional interface is added with Java version 8 given the need for Lambda expressions.
A functional interface keeps the same concept as an interface in previous versions of Java except that 2 rules are added**, and that is that for an interface to be functional it must:
- Have a only abstract method.
- A functional interface must implement the methods within the same interface (this could not be done in previous versions), for this the default reserved word must be placed before the beginning of the method declaration.
Although it is optional you can declare the annotation @FunctionalInterface, this annotation indicates to the compiler that this is a functional interface.
Java SE 8 defines four (4) large groups of functional interfaces grouped in the java.util.function package. Next we will see the main ones of each group:
- java.util.function.Consumer: Defines the +accept(T):void method and is used to consume methods of the T parameter, causing possible side effects.
- java.util.function.Supplier: Defines the +get():T method and is used for the creation of objects.
- java.util.function.Function<T, R>: Defines the +apply(T):R method and is used to convert from a T-value to another R-value.
- java.util.function.Predicate: Defines the +test(T):boolean method and is used for criteria validation.
These are those lambda expressions that accept a single value and do not return any value.
String message -> System.out.println(message);
BiConsumer expressions, a special case of consumer expressions, are those that take two values as a parameter and do not return results.
(String key, String value) -> System.out.println("Key: %s, value: %s%n", key, value);
In this case they are expressions that do not have parameters but return a result.
() -> return createRandomInteger()
Expressions that accept an argument and return a value as a result and whose types do not have to be the same.
Order persistedOrder -> persistedOrder.getIdientifier();
BiFunctions are function type expressions that accept two arguments and return a result.
(Address address, String name) -> new Person(name, address);
As in the case of Unarios Operators, this is a special case of functions in which the two arguments and the result are of the same type.
(String message, String anotherMesssage) -> message.concat(anotherMessage);
These are expressions that accept a parameter and return a logical value.
String message -> message.length > 50
As in the previous cases, you can have BiPredicados, predicates that instead of having one parameter, have two.
(path, attr) -> String.valueOf(path).endsWith(".js") && attr.size() > 1024