Using Java 8 Functional Interfaces to Replace if...else Statements
This article explains how Java 8’s Function functional interface and related interfaces such as Supplier, Consumer, and Runnable can replace traditional if‑else statements for exception handling and branching, providing concise code examples and utility methods for cleaner backend development.
Function Functional Interface
Java 8 introduced the @FunctionalInterface annotation to mark interfaces that contain a single abstract method, enabling lambda expressions. The main functional interfaces are Supplier (no arguments, returns a value), Consumer (accepts one argument, returns void), Runnable (no arguments, no return), and Function (accepts an argument and returns a value).
Replacing if…else with Function
Instead of writing repetitive if…else blocks that throw exceptions or perform branching, you can define a functional interface such as ThrowExceptionFunction that encapsulates the logic and invoke it via a lambda.
/*** 抛异常接口 ***/
@FunctionalInterface
public interface ThrowExceptionFunction {
void throwMessage(String message);
}
public static ThrowExceptionFunction isTrue(boolean b) {
return (errorMessage) -> {
if (b) {
throw new RuntimeException(errorMessage);
}
};
}Usage: VUtils.isTrue(condition).throwMessage("Error occurred"); – the method runs normally when the condition is false and throws an exception when true.
Branch handling
A BranchHandle interface can execute different Runnable actions based on a boolean value.
@FunctionalInterface
public interface BranchHandle {
void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}
public static BranchHandle isTrueOrFalse(boolean b) {
return (trueHandle, falseHandle) -> {
if (b) {
trueHandle.run();
} else {
falseHandle.run();
}
};
}Usage: VUtils.isTrueOrFalse(flag).trueOrFalseHandle(() -> doTrue(), () -> doFalse());
Present‑or‑Else handling
The PresentOrElseHandler interface processes a value that may be null, executing a Consumer when the value is present and a Runnable otherwise.
@FunctionalInterface
public interface PresentOrElseHandler
{
void presentOrElseHandle(Consumer
action, Runnable emptyAction);
}
public static PresentOrElseHandler
isBlankOrNoBlank(String str) {
return (consumer, runnable) -> {
if (str == null || str.length() == 0) {
runnable.run();
} else {
consumer.accept(str);
}
};
}Usage: VUtils.isBlankOrNoBlank(text).presentOrElseHandle(s -> System.out.println(s), () -> System.out.println("empty"));
By leveraging these functional interfaces, Java code becomes more expressive and less cluttered with repetitive conditional statements.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.