Replace Cluttered if…else with Java 8 Functional Interfaces
This article shows how to eliminate repetitive if…else statements in Java code by leveraging Java 8 functional interfaces such as Supplier, Consumer, Runnable, and custom interfaces for exception handling, branch processing, and null‑value handling, complete with code examples and diagrams.
In Java development, excessive if...else... statements can make code hard to read. Using Java 8 functional interfaces provides a cleaner alternative.
Function Functional Interface
Mark an interface with @FunctionalInterface to indicate it has a single abstract method. Common built‑in functional interfaces include:
Supplier : no arguments, returns a value.
Consumer : accepts one argument, returns void.
Runnable : no arguments, no return value.
Function : accepts one argument and returns a value.
Tip: Handling Exception‑Throwing if
1. Define a functional interface that throws an exception.
/** * 抛异常接口 */
@FunctionalInterface
public interface ThrowExceptionFunction {
void throwMessage(String message);
}2. Create a utility method that returns an instance based on a boolean flag.
public static ThrowExceptionFunction isTrue(boolean b) {
return (errorMessage) -> {
if (b) {
throw new RuntimeException(errorMessage);
}
};
}3. Use it:
ThrowExceptionFunction f = VUtils.isTrue(flag); f.throwMessage("error");Handling if‑branch with Functional Interfaces
1. Define a BranchHandle interface.
@FunctionalInterface
public interface BranchHandle {
void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}2. Utility method returning BranchHandle based on a condition.
public static BranchHandle isTrueOrFalse(boolean b) {
return (trueHandle, falseHandle) -> {
if (b) {
trueHandle.run();
} else {
falseHandle.run();
}
};
}PresentOrElse Handling for Nullable Values
1. Define a PresentOrElseHandler interface.
public interface PresentOrElseHandler<T extends Object> {
void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);
}2. Utility method that returns the handler based on string emptiness.
public static PresentOrElseHandler<?> isBlankOrNoBlank(String str) {
return (consumer, runnable) -> {
if (str == null || str.length() == 0) {
runnable.run();
} else {
consumer.accept(str);
}
};
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
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.
