Lamda表达式与函数式接口

126 阅读1分钟

Lamda表达式本质是一种语法糖,体现了流式编程的思想。
包含三部分:

  • 1、一个括号内用逗号分隔的形式参数,参数是函数式接口里面方法的参数
  • 2、一个箭头符号:->
  • 3、方法体,可以是表达式和代码块。
(parameters) -> expression 或者 (parameters) -> { parameters; }

总之,以上表达式的参数parameters和parameters分别代表了函数式接口中的方法的参数和返回值,但是整体表达式代表了该接口的实例化对象。


public class CheckUtils {
    private static final Function<String, String> lengthCheck = params -> {
        if (params.length() > 100) {
            throw new RuntimeException("Length exceed max limit.");
        }
        return params;
    };

    private static final Function<String, String> invalidCharacterCheck = str -> {
        if (!str.matches("^[a-f,A-F]$")) {
            throw new RuntimeException("Contains invalid character.");
        }
        return str;
    };
    
    /**
     * 这里的公共方法组合了该类中的基本校验逻辑构成一个复合的逻辑
     */
    public static void checkStringLengthAndPhoneNumber(String string) {
        invalidCharacterCheck.compose(lengthCheck).apply(string);
    }
}