What are Functional Interfaces
A functional interface is an interface with a single abstract method. That abstract method is used as the type of a lambda expression.
public interface ActionListner extends EventListener { public void actionPerformed( ActionEvent event); }
- It doesn't matter what the single method ( e.g. actionPerformed ) is called.
- The method will match up to lambda expression as long as it has compatible method signature
- One can see the type of the parameter in the functional interface => improves readability and understanding in code.
- Functional interfaces can use generics also.
- Some important functional interfaces in Java :
Interface Name | Arguments | Returns | Example |
---|---|---|---|
Predicate<T>sasdadas | Tdfasdfasdfafsadfs | booleanasfsdfsdadfsd | Has this book been published yet?aasdfsdfasdfasdfasdfasdfasdfasfsdfsfsdfsdadfsd |
Consumer<T> | T | void | Printing out a value. Getting an action/task done. |
Function<T,R> | T | R | Get a property/instance var from an object. Eg: get the author from book object |
Supplier<T> | None | T | Any Factory Method. Get Constant Values defined in certain context. |
UnaryOperator<T> | T | T | Logical not (!) |
BinaryOperator<T> (T,T) | (T,T) | T | Multiplying two numbers (*) |
- There are many interfaces in Java that encapsulates blocks of code such as "Runnable" or "Comparator"
- Lambdas are backwards compatible with these interfaces.
When to supply Lambda Expression?
- When an object of an interfaces with a single method is expected. Eg. ActionListerner is the functional interfaces in the following example: The Left Hand Side Code changes to written in Lambda expression in the right hand side.
- The boiler plate code is minimized, readability enhanced and meaningfulness accomplished.
button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event){ System.out.println("Click on Button"); } }) | button.addActionListerner( event -> System.out.println("Click on Button"); ) |
No comments:
Post a Comment