java support for functional programming

java support for functional

Java8 provides lambda expressions, method references, and predefined functional interfaces to adapt to functional programming.

Java regards lambda expressions as object instances of functional interfaces, but this is 一等值a concept that has been satisfied at the design level .

Functional interface

jdk has provided a series of functional interfaces ( Package java.util.function ), such as Consumer, Supplier, Function, Predicate and other DoubleConsumer, IntPredicate, and BiConsumer based on multi-parameters due to the performance loss of unboxing and packing Wait.

If functionthe interface under the package does not meet your needs, you can @FunctionalInterfacedeclare your own functional interface in cooperation with Sanchong . For functional interfaces, @FunctionalInterfaceit can be added or not. Its function is to see if you 函数式接口have only one instance method at compile time .

Because in Java, functional support is implemented by instantiating functional interfaces (often based on lambda expressions).

// 自定义消费int的函数式接口
@FunctionalInterface
interface consumeInt {
    
    
    void consume(int i);
}
// 实例化函数式接口
consumeInt consumeInt = i -> System.out.println(i);

lambda expression

The syntax of lambda expressions is simple:

(parameters) -> expression // 若只有一条执行语句的话不带{}(parameters) ->{
    
     statements; } // 多条执行语句带{},且带;

The lambda expression will automatically infer the type of the parameter. Generally speaking, it depends on the parameter types specified by the functional interface, but with the use of the java paradigm, lambda expressions have more expressive capabilities:

Function<String, String> function = str -> // 使用范型指定传入String 传出String
    new StringBuilder(str).append("-").append(str.length()).toString();
// 当然也可以手动指定类型
Function<String, String> function = (String str)->...

Method reference

Reference article

Method references can be divided into four categories: those that point to static methods, those that point to instance methods of variables in lambda expressions, those that point to instance methods of external objects, and those that point to constructors.

The declaration of a method in Java includes six aspects: modifiers, return values, method names, method parameters, exception lists, and method bodies. When using method references:

  1. Modifiers should be compound conditions (methods that cannot be accessed and natural method references are not available)
  2. Ensure that the method signature matches (the method signature contains the return value and method parameters)
  3. Ensure compatibility of the exception list. (Requires that the referenced method is smaller than the required method exception list)
public class FunctionRefSt {
    
    
  	// 静态方法
    public static int length(String str) {
    
    
        return str.length();
    }
		// 实例方法
    public int lengthIns(String str) {
    
    
        return str.length();
    }
		// 四种引用的展示
    @Test
    public void funcRef() {
    
    
        Optional<String> opt = Optional.of("hello world");
        /*以下三种输出都是11*/
        // 静态方法引用
        opt.map(FunctionRefSt::length).ifPresent(System.out::println);
        // 内部实例方法引用
        opt.map(String::length).ifPresent(System.out::println);
        // 外部实例方法引用
        FunctionRefSt functionRefSt = new FunctionRefSt();
        opt.map(functionRefSt::lengthIns).ifPresent(System.out::println);

        /*构造函数引用实例*/
        // 利用optional避免空指针
				System.out.println(Optional.<List>ofNullable(null).orElseGet(/*引用了构造方法*/ArrayList::new).size());
	      //输出0
    }
}

Pattern matching

模式匹配It can be simply understood as an 增强switchexpression. java8 currently does not support pattern matching, that switch can support the type of match is still relatively small: 枚举、String、byte、short、int、char以及一些基本类型的包装类. After java12, switch expressions have been optimized, jdk13switch features :

// jdk12
switch (type) {
    
    
    case "all" -> System.out.println("列出所有帖子");
    case "auditing" -> System.out.println("列出审核中的帖子");
    case "accepted" -> System.out.println("列出审核通过的帖子");
    case "rejected" -> System.out.println("列出审核不通过的帖子");
    default -> System.out.println("参数'type'错误,请检查");
}
// jdk13
String value = switch (i) {
    
    
    case  0 -> "zero"
    case  1 -> "one"
    case  2 -> "two"
    default -> "many"
};
System.out.println(value);

Guess you like

Origin blog.csdn.net/qq_38619183/article/details/112482404