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

  • A+

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!


One of the primary use that they've provided is that the instances of functional interfaces can be created with lambda expressions and method references as well as using a constructor at the same time. For example, a functional interface Sample defined as:

@FunctionalInterface public interface Sample {     void ab(); } 

can be instantiated in as simple as a single line of code as :

Sample sample = () -> System.out.println("ab called"); 

and then called wherever required as:


I would further quote the Javadoc from the java.util.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.filter(e -> e.getSize() > 10)...   // Cast context e -> e.getSize())... 

Furthermore, such interfaces could be annotated with @FunctionalInterface annotation.

This annotation is not a requirement for the compiler to recognize an interface as a functional interface, but merely an aid to capture design intent and enlist the help of the compiler in identifying accidental violations of design intent.

Also a worthy point for using the concepts with existing such interfaces,

the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: