Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real world example of using a functional interface in Java [closed]

I know a functional interface means you can have exactly/only 1 abstract method with more than 1 default method(s) but I am wondering how to relate to it with a real-world example/situation of using a functional interface in Java.

Could you give a valid situation/example?

Thanks in advance!

like image 595
Arun Kumar Avatar asked Jan 02 '19 09:01

Arun Kumar


People also ask

What is the use of functional interface in real time?

function package: Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context: // Assignment context Predicate<String> p = String::isEmpty; // Method invocation context stream.

When should we use functional interface in Java?

Objects are the base of java programming language and we can never have a function without an Object, that's why Java language provide support for using lambda expressions only with functional interfaces.

What are the uses of functional interface?

A functional interface is a special kind of interface with exactly one abstract method in which lambda expression parameters and return types are matched. It provides target types for lambda expressions and method references.


2 Answers

First of all annotation @FunctionalInterface is used by Java's built-in functional interfaces Predicate,Function,Consumer, etc...

From the other hand you may want to create your custom one like the following:

@FunctionalInterface
public interface ThrowingConsumer<T> {
    void accept(T t) throws CustomException;
}

Then you can use it as a method parameter:

public <T, R> void doSomething(T value, ThrowingConsumer<T, R> consumer) {
    // ...
}

And then call it like this:

doSomething(someValue, this::customConsumerMethodThrowingAnException);

It is worth to mention that @FunctionalInterface is not required. The compiler will be perfectly fine with any interface meeting the requirements.

The compiler treats it in a way similar to dealing with @Override annotation. The code compiles even without it. But once added it makes the code clearer and safer for the ones who will maintain the code in the future.

like image 164
ETO Avatar answered Oct 31 '22 12:10

ETO


We've always had functional interfaces before JDK8 but no lambdas, method references etc.

As of JDK8, they provide a target type for lambda expressions, method references and in turn, have better readability and more compact code.

Example, prior to Java-8 if you wanted to provide some logic that will be executed each time a Button component is clicked you'd do:

 btn.setOnAction(new EventHandler<ActionEvent>() { 
       @Override
       public void handle(ActionEvent event) {
            System.out.println("Hello World!");
       }
 });

This is bulky, hard to read and not compact enough. because EventHandler is by definition a functional interface i.e. it has a SAM as of jdk8 you can now do:

btn.setOnAction(event -> System.out.println("Hello World!"));

You only see the part of the code you care about i.e. the logic to be executed when the button is clicked.

Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when:

  • passing a comparator to a sort method e.g. List.sort, Stream.sorted, Collections.sort etc.
  • passing a block of code to run a task in a separate thread

etc...

while keeping the code readable, compact and concise.

Functional interfaces are used extensively in the Java-stream API.

There's no reason for you to create your own functional interface except there's not one that meets your requirements from java.util.function or the name of the functional interface is not as readable so thus you may create your own.


There's also a @FunctionalInterface annotation recommended to be used but not required whenever you're creating a functional interface (the standard library uses this a lot).

This enables the compiler to check that the annotated entity is an interface with a single abstract method otherwise gives an error.

This is also quite helpful in being able to catch errors when refactoring your code.

like image 29
Ousmane D. Avatar answered Oct 31 '22 13:10

Ousmane D.