Real world example to use Functional Interface in Java

  • A+
Category:Languages

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 to relate it with a real-world example/Situation to use functional interface in Java.

Could you list down 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:

sample.ab(); 

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  stream.map((ToIntFunction) e -> e.getSize())... 

Comment

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