Fundamentals 6 min read

How to Replace Cluttered if…else… with Java 8 Functional Interfaces

This article explains how to eliminate repetitive if‑else statements in Java by leveraging Java 8's functional interfaces such as Supplier, Consumer, Runnable, and Function, providing reusable lambda‑based utilities for exception handling and branch processing with clear code examples.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
How to Replace Cluttered if…else… with Java 8 Functional Interfaces

Function Functional Interface

In development, if...else... statements for throwing exceptions or handling branches clutter code; Java 8's Function functional interface can replace them.

Using Annotations

Mark an interface with @FunctionalInterface; it must contain a single abstract method, making it a functional interface. Common functional interfaces include 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 seen as a conversion function.

Supplier (Supply‑type Function)

Represents a function that takes no parameters and returns data.

Consumer (Consume‑type Function)

Opposite of Supplier; accepts a parameter and returns nothing.

Runnable (No‑arg, No‑return Function)

Has neither parameters nor a return value.

Function (Argument‑to‑Result Function)

Accepts one argument and returns a value; it can be considered a special form of the other functional interfaces.

Practical Tips

Handling Exception‑Throwing if

@FunctionalInterface
public interface ThrowExceptionFunction {
    /**
     * Throw an exception with a message
     */
    void throwMessage(String message);
}

Utility method that returns a ThrowExceptionFunction which throws an exception when the boolean parameter is true:

public static ThrowExceptionFunction isTure(boolean b) {
    return (errorMessage) -> {
        if (b) {
            throw new RuntimeException(errorMessage);
        }
    };
}

Branch Handling

@FunctionalInterface
public interface BranchHandle {
    /**
     * Execute different actions based on a boolean value
     */
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}
public static BranchHandle isTureOrFalse(boolean b) {
    return (trueHandle, falseHandle) -> {
        if (b) {
            trueHandle.run();
        } else {
            falseHandle.run();
        }
    };
}

Present‑or‑Else Handling

@FunctionalInterface
public interface PresentOrElseHandler<T extends Object> {
    /**
     * Execute <code>action</code> when value is present, otherwise run <code>emptyAction</code>
     */
    void presentOrElseHandle(Consumer<? super T> 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 examples show how to pass lambda expressions to these utilities, simplifying exception throwing and branch logic without explicit if…else blocks.

Conclusion

Function

functional interfaces are a crucial feature of Java 8; using them effectively can greatly simplify code by removing repetitive conditional statements.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaException HandlingLambdaFunctional Interfacebranching
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.