Java Functional Interface Tutorial with Examples
1. Functional Interface
No ADS
Functional Interface is a new concept introduced in Java since version 8, which is an interface with only one abstract method. Lambda expressions are often used to quickly create an object of a Functional Interface.
Here is a Functional Interface, with a single abstract method:
package org.o7planning.ex;
public interface Greeting {
String greeting(String name);
default String hello(String name) {
return "Hello " + name;
}
}
If an interface is designed for the purpose of a functional interface, you should use @FunctionalInterface annotation to annotate it. Although this is not required, it makes it easier for others to understand your design idea. It also assists compiler to report your errors during application development. For example, compiler will flag error if there is an interface annotated by @FunctionalInterface but has more than one abstract method.
package org.o7planning.ex;
@FunctionalInterface
public interface Greeting {
String greeting(String name);
default String hello(String name) {
return "Hello " + name;
}
}
Continue with the above example. Before Java 8, to create a Greeting object you had to create a class and then implement Greeting's abstract method, which is quite verbose.
UsingGreetingBeforeJ8.java
package org.o7planning.ex;
public class UsingGreetingBeforeJ8 {
public static void main(String[] args) {
// Create Greeting object:
Greeting obj = new Greeting() {
@Override
public String greeting(String name) {
return "Hi " + name;
}
};
System.out.println(obj.greeting("Tran"));
System.out.println(obj.hello("Tran"));
}
}
Basically, Functional Interface includes only 1 abstract method, so you only need to implement this method. Java 8 Lambda Expression helps you to rewrite the previous example more concisely.
UsingGreetingJ8A.java
package org.o7planning.ex;
public class UsingGreetingJ8A {
public static void main(String[] args) {
// Create Greeting object with Lambda expression:
Greeting obj = (String name) -> {
return "Hi " + name;
};
System.out.println(obj.greeting("Tran"));
System.out.println(obj.hello("Tran"));
}
}
Datatypes of the parameters in Greeting's abstract method are known, so there's no need to rewrite them. We can rewrite the previous example more succinctly:
Greeting obj = (name) -> {
return "Hi " + name;
};
If abstract method has only one parameter, you probably don't need parentheses () in Lambda expression:
Greeting obj = name -> {
return "Hi " + name;
};
If the method's contents consist of only one expression, you may not need braces {} nor need to write keyword "return".
Greeting obj = name -> "Hi " + name;
Finally, code of previous example is much shorter:
UsingGreetingJ8.java
package org.o7planning.ex;
public class UsingGreetingJ8 {
public static void main(String[] args) {
// Create Greeting object with Lambda expression:
Greeting obj = name -> "Hi " + name;
System.out.println(obj.greeting("Tran"));
System.out.println(obj.hello("Tran"));
}
}
Output:
Hi Tran
Hello Tran
2. Examples
No ADS
Next, we will look at some Functional Interface(s) including valid and invalid, and explain why they are invalid:
The following IEquals interface is not a functional interface because the method "public boolean equals (Object)" is a member inherited from Object class. Thus IEquals is considered to have no abstract methods and is ineligible for a functional interface.
IEquals.java (Invalid!)
package org.o7planning.j8fi;
@FunctionalInterface
public interface IEquals {
boolean equals(Object other);
}
Valid:
IComparator.java (OK, Valid!)
package org.o7planning.j8fi;
@FunctionalInterface
public interface IComparator<T> {
int compareTwoObject(T obj, T other);
boolean equals(Object other);
}
clone() method of Object class is protected (Not public). Therefore the following IWithClone interface is considered a valid functional interface.
IWithClone.java (OK, Valid)
package org.o7planning.j8fi;
@FunctionalInterface
public interface IWithClone {
Object clone();
}
CC interface in the above illustration is a valid functional interface because abstract methods that it inherits from AA and BB are the same.
No ADS
Java Basic
- Data Types in java
- Java PhantomReference Tutorial with Examples
- JDK Javadoc in CHM format
- Java Stream Tutorial with Examples
- Java Predicate Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- Arrays in Java
- JDBC Driver Libraries for different types of database in Java
- Abstract class and Interface in Java
- Java Commons Email Tutorial with Examples
- Install Eclipse
- Bitwise Operations
- Install Eclipse on Ubuntu
- Configuring Eclipse to use the JDK instead of JRE
- Java Commons Logging Tutorial with Examples
- Java Enums Tutorial with Examples
- Loops in Java
- Java Regular Expressions Tutorial with Examples
- Install Java on Ubuntu
- Quick Learning Java for beginners
- Install Java on Windows
- Comparing and Sorting in Java
- Inheritance and polymorphism in Java
- Java Consumer Tutorial with Examples
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- if else statement in java
- Switch Statement in Java
- Java Supplier Tutorial with Examples
- Java Programming for team using Eclipse and SVN
- Java JDBC Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- What is needed to get started with Java?
- Java Aspect Oriented Programming with AspectJ (AOP)
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java Compression and Decompression Tutorial with Examples
- Java Reflection Tutorial with Examples
- Install OpenJDK on Ubuntu
- Java String.format() and printf() methods
- History of Java and the difference between Oracle JDK and OpenJDK
- Introduction to the Raspberry Pi
- Java Socket Programming Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java WeakReference Tutorial with Examples
- Java Commons IO Tutorial with Examples
- History of bits and bytes in computer science
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java SoftReference Tutorial with Examples
- Syntax and new features in Java 8
- Java Annotations Tutorial with Examples
- Java Function Tutorial with Examples
- Access modifiers in Java
- Java BiFunction Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Functional Interface Tutorial with Examples
- Java BiPredicate Tutorial with Examples
Show More
- Java Servlet/Jsp Tutorials
- Java Collections Framework Tutorials
- Java API for HTML & XML
- Java IO Tutorials
- Java Date Time Tutorials
- Spring Boot Tutorials
- Maven Tutorials
- Gradle Tutorials
- Java Web Services Tutorials
- Java SWT Tutorials
- JavaFX Tutorials
- Java Oracle ADF Tutorials
- Struts2 Framework Tutorials
- Spring Cloud Tutorials