Functional Interface in Java
Java Functional Interfaces
A practical guide to lambdas, method references and common functional interfaces in Java.
1. What Is a Functional Interface?
A functional interface has exactly one abstract method, also called a Single Abstract Method (SAM). It can be the target type of a lambda expression or a compatible method reference.
- Default and static methods have implementations and do not count as abstract methods. The
abstractkeyword on an interface's abstract methods is optional. - An abstract method matching a public method of
java.lang.Object, such asequals(Object), does not count toward the functional method. Inherited abstract methods also matter. @FunctionalInterfaceis optional but asks the compiler to check that the interface is functional. The annotation does not itself make an interface functional.
.java file named after its public class; compile with javac FileName.java and run with java ClassName.2. Custom Interface and Lambda
A lambda supplies an instance of a functional interface. You can also pass that behavior as a method argument. Here add is the only functional method.
Example: pass an addition operation
public class AdditionExample {
@FunctionalInterface
interface Addition {
int add(int a, int b);
boolean equals(Object other);
default int addOne(int value) {
return add(value, 1);
}
static String name() {
return "addition";
}
}
static int calculate(int a, int b, Addition operation) {
return operation.add(a, b);
}
public static void main(String[] args) {
Addition sum = (a, b) -> a + b;
System.out.println(calculate(3, 4, sum));
System.out.println(sum.addOne(9));
System.out.println(Addition.name());
}
}
Output:
7
10
addition
@FunctionalInterface.3. Runnable and Threads
Runnable has one abstract method, run(). Existing interfaces such as Runnable can also be used with lambdas. In this example, join() waits for the worker to finish.
public class RunnableExample {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("New thread created Lambda");
Thread worker = new Thread(task);
worker.start();
worker.join();
}
}
Output:
New thread created Lambda
4. Consumer and Method References
Consumer<T> accepts one input and returns no result from accept(T). It is commonly used for printing or other side effects. IntConsumer, LongConsumer and DoubleConsumer are primitive specializations.
Example: sum a list and print a message
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerExample {
static void printSum(List<Integer> values) {
int sum = values.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum of list values: " + sum);
}
public static void main(String[] args) {
List<Integer> values = Arrays.asList(10, 20, 30, 40);
Consumer<List<Integer>> sum = ConsumerExample::printSum;
sum.accept(values);
Consumer<String> print = System.out::println;
print.accept("javaA143mk");
}
}
Output:
Sum of list values: 100
javaA143mk
:: is method-reference syntax. The referenced method must be compatible with the target functional interface's parameters and return type.
5. Predicate and Class Implementation
Predicate<T> tests an input and returns a boolean from test(T). Combine conditions with and, or and negate. It can be implemented by a lambda or a regular class.
import java.util.function.Predicate;
public class PredicateExample {
static class Adult implements Predicate<Integer> {
@Override
public boolean test(Integer age) {
return age >= 18;
}
}
public static void main(String[] args) {
Predicate<Integer> adult = new Adult();
Predicate<Integer> under65 = age -> age < 65;
System.out.println(adult.test(10));
System.out.println(adult.and(under65).test(25));
System.out.println(adult.negate().test(10));
}
}
Output:
false
true
true
NullPointerException during unboxing. Validate inputs as required by your application.6. Other Common Functional Interfaces
| Interface | Abstract method | Typical use |
|---|---|---|
| Function<T, R> | apply(T) | Transform an input into a result. |
| Supplier<T> | get() | Supply a value without an input. |
| Consumer<T> | accept(T) | Perform a side effect with an input; return no value. |
| Predicate<T> | test(T) | Decide true or false about an input. |
| UnaryOperator<T> | apply(T) | Transform one value with the same input and result type. |
| BinaryOperator<T> | apply(T, T) | Combine two values of the same type into a result of that type. |
Other examples include Runnable, Callable, Comparator, Comparable and ActionListener. Function, Supplier, Consumer and Predicate are in java.util.function.
Example: Function, Supplier and BinaryOperator
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
public class FunctionExample {
public static void main(String[] args) {
Function<String, Integer> length = String::length;
Supplier<String> greeting = () -> "Java";
BinaryOperator<Integer> sum = Integer::sum;
System.out.println(length.apply(greeting.get()));
System.out.println(sum.apply(2, 3));
}
}
Output:
4
5
7. Marker Interfaces: A Different Concept
A marker interface is used to mark a type and typically declares no methods. A functional interface has one abstract method, so an empty marker interface is not itself a functional interface and cannot be the target of a lambda.
Example: recognize a marked type
public class MarkerExample {
interface Car { }
interface Engine { }
static class Vehicle implements Car { }
static class EngineStatus implements Engine { }
public static void main(String[] args) {
Object vehicle = new Vehicle();
Object status = new EngineStatus();
System.out.println(vehicle instanceof Car);
System.out.println(status instanceof Engine);
}
}
Output:
true
true
Serializable, Cloneable and Remote are well-known marker interfaces. Their meaning is defined by the relevant Java APIs; declaring your own marker does not automatically add behavior. For example, implementing Cloneable alone does not provide a public clone() method.
For more details, see the FunctionalInterface API and java.util.function documentation.
Good to see 👀
ReplyDelete