Using Java 8 Functional Interfaces to Replace if…else Statements
This article explains how Java 8's functional interfaces such as Supplier, Consumer, Runnable and Function can be used to eliminate repetitive if…else code for exception handling and branching, providing clear examples and reusable utility methods.
During development, if...else... statements are frequently used for throwing exceptions and handling branches, which can clutter code. Java 8's Function interface allows you to replace these repetitive if...else... constructs.
if (...){
throw new RuntimeException("出现异常了");
}
if (...){
doSomething();
} else {
doOther();
}Function Functional Interface
By annotating an interface with @FunctionalInterface and ensuring it contains only one abstract method, you create a functional interface. The main types are Supplier (no arguments, returns a value), Consumer (accepts an argument, returns nothing), Runnable (no arguments, no return), and Function (accepts an argument and returns a value).
Function can be regarded as a transformation function.
Supplier (Provider) Function
A Supplier does not accept parameters and only returns data.
Consumer (Consumer) Function
A Consumer is the opposite of Supplier: it accepts one argument and returns nothing.
Runnable (No‑arg No‑return) Function
Runnable has neither parameters nor a return value.
Function itself accepts one argument and returns a value. Supplier , Consumer and Runnable can be seen as special forms of Function .
Tips
Handling Exception‑Throwing if
1. Define the functional interface
/**
* Throw exception interface
*/
@FunctionalInterface
public interface ThrowExceptionFunction {
/**
* Throw an exception message
* @param message exception message
*/
void throwMessage(String message);
}2. Write a helper method
/**
* Returns a ThrowExceptionFunction that throws when the argument is true
*/
public static ThrowExceptionFunction isTrue(boolean b) {
return (errorMessage) -> {
if (b) {
throw new RuntimeException(errorMessage);
}
};
}3. Usage
Call the utility method and then invoke throwMessage with the desired error text. The method executes normally when the condition is false and throws an exception when true.
Handling if‑branch operations
1. Define a functional interface
/**
* Branch handling interface
*/
@FunctionalInterface
public interface BranchHandle {
/**
* Execute different actions based on a boolean value
* @param trueHandle action when true
* @param falseHandle action when false
*/
void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}2. Write a helper method
/**
* Returns a BranchHandle that runs the appropriate Runnable
*/
public static BranchHandle isTrueOrFalse(boolean b) {
return (trueHandle, falseHandle) -> {
if (b) {
trueHandle.run();
} else {
falseHandle.run();
}
};
}3. Usage
When the parameter is true, the trueHandle runs; otherwise, the falseHandle runs.
Present‑or‑Else handling for optional values
1. Define the functional interface
/**
* Handles present and empty values
*/
public interface PresentOrElseHandler
{
/**
* Executes a Consumer when the value is present, otherwise runs a Runnable
* @param action action for non‑null value
* @param emptyAction action for null or empty value
*/
void presentOrElseHandle(Consumer
action, Runnable emptyAction);
}2. Write a helper method
/**
* Returns a handler that distinguishes between blank and non‑blank strings
*/
public static PresentOrElseHandler
isBlankOrNoBlank(String str) {
return (consumer, runnable) -> {
if (str == null || str.length() == 0) {
runnable.run();
} else {
consumer.accept(str);
}
};
}3. Usage
Pass a Consumer to process a non‑empty value and a Runnable for the empty case.
Conclusion
The Function functional interface is a crucial feature of Java 8; leveraging it can dramatically simplify code and improve readability.
Will you try this approach in your own code? Feel free to leave a comment with your thoughts!
PS: If you found this share useful, please give it a like and a view.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.