Use the Function interface in Java 8 to eliminate if…else (a very novel way of writing)

ee2878a017473127f0412cce452fd81c.jpegSource: juejin.cn/post /7011435192803917831

Welcome to join Xiaoha’s Planet, you will get: Exclusive project practice/Java learning route/One-on-one questions/Learning check-in/Gift book benefits

Currently, I am leading my friends to work on the first project within the planet: Full StackSeparation of front-end and back-end blog, hands-on, back-end + front-end full-stack development, from 0 to 1 Explain the development steps of each function point and answer questions 1v1 until the project goes online. At present, 125 sections have been updated, with a total of 190,000+ words, and 805 explanation pictures. It is still being updated. More projects will be added in the future. The goal is to complete a wave of typical projects in the Java field, such as flash sales. System, online mall, IM instant messaging, Spring Cloud Alibaba, etc., click me to join the learning, 410+ friends have joined (early bird price is super low)

  • Function Functional interface

    • SupplierSupply function

    • ConsumerConsumption function

    • RunnableNo parameters and no return function

    • FunctionThe expression of a function is to receive a parameter and return a value. Supplier, Consumer and Runnable can be regarded as a special representation of Function

  • Use tips

    • Handle if that throws an exception

    • Handle if branch operations

    • If a value exists, perform a consumption operation, otherwise perform a null-based operation.

In the development process, if...else... is often used to judge and throw exceptions, branch processing and other operations. These if...else... are flooded in the code and seriously affect the appearance of the code. At this time, we can use the FunctionJava 8 >Interface to eliminate if...else....

if (...){
    throw new RuntimeException("An exception occurred");
}

if (...){
    doSomething();
} else {
    doOther();
}

Function Functional interface

An interface marked with the annotation @FunctionalInterface and containing only one abstract method is a functional interface. Functional interface is mainly divided into Supplier supply function, Consumer consumption function, Runnable no parameter and no return type Functions and Function have parameters and return functions.

Function can be regarded as a conversion function

SupplierSupply function

The expression form of Supplier is that it does not accept parameters and only returns data.

3c57a4c808d2439fa9d8da55d60e9082.jpeg

picture

ConsumerConsumption function

Consumer consumer functions are just the opposite of Supplier. Consumer receives one parameter and has no return value

65bca165099b682b6ee8678d286b6e35.jpeg

picture

RunnableNo parameters and no return function

The expression form of Runnable is that it has no parameters and no return value.

0223bbfb3336e88bf6c39af6ef668f86.jpeg

picture

FunctionThe expression of a function is to receive a parameter and return a value. Supplier, Consumer and Runnable can be regarded as a special expression of Function

b636ee7b96274c74526c2a10790946af.jpeg

picture

Tips

Handling if exceptions thrown

  1. define function

Define a functional interface in the form of throwing an exception. This interface has only parameters and no return value. It is a consumer interface

/**
 *Exception throwing interface
 **/
@FunctionalInterface
public interface ThrowExceptionFunction {

    /**
     * Throw exception information
     *
     * @param message exception information
     * @return void
     **/
    void throwMessage(String message);
}
  1. Write a judgment method

Create a tool class VUtils and create a isTure method. The return value of the method is the Functional InterfaceThrowExceptionFunction just defined. >. The interface implementation logic of ThrowExceptionFunction is to throw an exception when the parameter b is true

/**
 * Throws an exception if the parameter is true
 *
 * @param b
 * @return com.example.demo.func.ThrowExceptionFunction
 **/
public static ThrowExceptionFunction isTure(boolean b){

    return (errorMessage) -> {
        if (b){
            throw new RuntimeException(errorMessage);
        }
    };
}
  1. Usage

After calling the tool class parameters, call the throwMessage method of Functional Interface to pass in the exception information. Normal execution when the incoming and outgoing parameters are false

57a1a6dccfdfd4b6409944b16402f5d2.jpeg

picture

An exception is thrown when the incoming and outgoing parameters are true

bbf777ac5d8f9edda9bd2e4974a71802.jpeg

picture

Processing if branch operations

  1. Define functional interface

Create a functional interface named BranchHandle. The parameters of the interface are two Runnable interfaces. These two Runnable interfaces respectively represent the operations to be performed when it is true or false

/**
 * Branch processing interface
 **/
@FunctionalInterface
public interface BranchHandle {

    /**
     * Branch operations
     *
     * @param trueHandle The operation to be performed when it is true
     * @param falseHandle The operation to be performed when it is false
     * @return void
     **/
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);

}
  1. Write a judgment method

Create a method named isTureOrFalse. The return value of the method is the Functional InterfaceBranchHandle just defined.

/**
 * When the parameter is true or false, different operations are performed respectively.
 *
 * @param b
 * @return com.example.demo.func.BranchHandle
 **/
public static BranchHandle isTureOrFalse(boolean b){
    
    return (trueHandle, falseHandle) -> {
        if (b){
            trueHandle.run();
        } else {
            falseHandle.run();
        }
    };
}
  1. Usage

When the parameter is true, execute trueHandle

e5c265717a1ded72b0168149b0fdfbb0.jpeg

picture

When the parameter is false, execute falseHandle

3b437d9cc1d3af7a094ff3c58b4dcedf.jpeg

picture

If the value exists, perform the consumption operation, otherwise perform the null-based operation

  1. define function

Create a functional interface named PresentOrElseHandler. One parameter of the interface is the Consumer interface. One is Runnable, which respectively represent consumption operations performed when the value is not empty and other operations performed when the value is empty.

/**
 * Null value and non-null value branch processing
 */
public interface PresentOrElseHandler<T extends Object> {

    /**
     * Execute consumption operation when the value is not empty
     * Perform other operations when the value is empty
     *
     * @param action The consumption operation performed when the value is not empty
     * @param emptyAction The action to be performed when the value is empty
     * @return void
     **/
   void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);
   
}
  1. Write a judgment method

Create a method named isBlankOrNoBlank. The return value of the method is the Functional InterfacePresentOrElseHandler just defined.

/**
 * When the parameter is true or false, different operations are performed respectively.
 *
 * @param b
 * @return com.example.demo.func.BranchHandle
 **/
public static PresentOrElseHandler<?> isBlankOrNoBlank(String str){

    return (consumer, runnable) -> {
        if (str == null || str.length() == 0){
            runnable.run();
        } else {
            consumer.accept(str);
        }
    };
}
  1. Usage

After calling the tool class parameters, call the presentOrElseHandle method of Functional Interface and pass in a Consumer and Runnable

When the parameter is not empty, print the parameter

fc741094d2e7d75a7ae5b2ac3b5f1f99.jpeg

picture

When the parameter is not empty

cf482122de30a8b51c2163d280f094f5.jpeg

picture

Welcome to join Xiaoha’s Planet, you will get: Exclusive project practice/Java learning route/One-on-one questions/Learning check-in/Gift book benefits

Currently, I am leading my friends to work on the first project within the planet: Full StackSeparation of front-end and back-end blog, hands-on, back-end + front-end full-stack development, from 0 to 1 Explain the development steps of each function point and answer questions 1v1 until the project goes online. At present, 125 sections have been updated, with a total of 190,000+ words, and 805 explanation pictures. It is still being updated. More projects will be added in the future. The goal is to include all typical projects in the Java field, such as flash sales. System, online mall, IM instant messaging, Spring Cloud Alibaba, etc., click me to join the learning, 410+ friends have joined (early bird price is super low)


049c21f3c5794b5d57b16d953 0a830df.png


f65379f71a1a7d7d8158c54f2420bf1a.gif




1. My private study circle~

2. To understand how to live in a different place, just read this article

3. The comparison between Chinese and American programmers is too real. . .

4. Top tool, a powerful Java entity conversion/copying tool

cd1ab70e2e83ef0f6f064dd93c8f55b2.gif

I recently interviewed BAT and compiled an interview material "Java Interview BATJ Clearance Manual", which covers Java core technology, JVM, Java concurrency, SSM, microservices, databases, data structures, etc.
How to get it: Click "Watching", follow the official account and reply to Java to get it. More content will be provided one after another. 
PS: Because the official account platform has changed the push rules, if you don’t want to miss the content, remember to click “Reading” after reading and add a “star”, so that each new article will be pushed to you as soon as possible. in the subscription list.
Click "Watching" to support Xiaoha, thank you