Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

It is common to use if… else… To determine the throw exception, branch processing and other operations. The if… else… We can use Java 8’s Function interface to eliminate if… else… .

if(...). {throw new RuntimeException("Something's wrong.");
} 

if(...). { doSomething(); }else {
    doOther();
}
Copy the code

FunctionFunctional interface

An interface identified by the @functionalinterface annotation and containing only one abstract method is a FunctionalInterface. Functional interfaces are mainly divided into Supplier functions, Consumer functions, Runnable functions without parameters and return functions, and Function functions with parameters and return functions.

Function can be thought of as a conversion Function

SupplierSupply function

Supplier“Takes no parameters and returns only data

ConsumerConsumptive function

The Consumer function is the opposite of Supplier. The Consumer receives an argument with no return value

RunnableNo parameter, no return function

RunnableIs in the form of no arguments and no return value

FunctionThe function takes an argument and returns a value.Supplier,ConsumerandRunnableCan be seen asFunctionA special form of expression

Use tricks

Handle the if that throws an exception

  1. Define a function

Defines a functional interface that throws an exception. This interface has only parameters and no return values

/** * throw exception interface **/
@FunctionalInterface
public interface ThrowExceptionFunction {

    /** * Throws an exception message **@paramMessage Abnormal message *@return void
     **/
    void throwMessage(String message);
}
Copy the code
  1. Write a judgment method

Create the utility class VUtils and create an isTure method that returns the functional interface you just defined -ThrowExceptionFunction. The interface to ThrowExceptionFunction implements the logic to throw an exception if parameter B is true

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

    return (errorMessage) -> {
        if (b){
            throw newRuntimeException(errorMessage); }}; }Copy the code
  1. use

Call after calling the utility class parameter parameterFunctional interfacethethrowMessageMethod passes in an exception message. When the inbound and outbound parameters arefalseNormal execution when

When the inbound and outbound parameters aretrueThrows an exception when

Handle if branch operations

  1. Define functional interfaces

Create a functional interface named BranchHandle with two Runnable interfaces as parameters. These two Runnable interfaces represent the operations to be performed when true or false, respectively

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

    /** * Branch operation **@paramThe operation to perform when trueHandle is true *@paramFalseHandle Specifies the operation to perform when falseHandle is false *@return void
     **/
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);

}
Copy the code
  1. Write a judgment method

Create a method called isTureOrFalse that returns the function interface you just defined -BranchHandle.

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

Parameters fortrueWhen performingtrueHandle

Parameters forfalseWhen performingfalseHandle

Perform a consumption operation if a value is present, perform a null-based operation otherwise

  1. Define a function

Create a functional interface called PresentOrElseHandler with one of the arguments to the Consumer interface. One, Runnable, represents the consumption operation performed when the value is not null and the other operations performed when the value is null

/** * null and non-null branches */
public interface PresentOrElseHandler<T extends Object> {

    /** * perform the consume operation if the value is not null ** perform other operations if the value is null **@paramAction The consumption action performed when the value is not empty *@paramThe action performed when emptyAction is empty@return void    
     **/
   void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);
   
}
Copy the code
  1. Write a judgment method

Create a method named isBlankOrNoBlank that returns the function interface you just defined -PresentOrElseHandler.

/** * When the argument is true or false, different operations are performed **@param b
 * @return com.example.demo.func.BranchHandle
 **/
public staticPresentOrElseHandler<? > isBlankOrNoBlank(String str){return (consumer, runnable) -> {
        if (str == null || str.length() == 0){
            runnable.run();
        } else{ consumer.accept(str); }}; }Copy the code
  1. use

After calling the utility class argument, the presentOrElseHandle method that calls the functional interface passes in a Consumer and Runnable

If the parameter is not empty, print the parameter

Parameter is not null

At the end

The Function interface is a very important feature of Java 8, and taking advantage of the Function Function can greatly simplify code.