Java8 - java.util.function.Function 接口教程及实例

658 阅读2分钟

java util 函数类

这是一个简单的函数接口,方法的输入和输出都由它来完成。这个接口用于映射对象--它接受一种类型的输入,处理它并返回另一种类型的输出。这个接口只有一个抽象方法:java.util.function.function是java 8中引入的预定义接口。

这篇文章是关于预定义的功能接口--函数的例子与教程。还用例子解释了apply(), andThen(), componse()方法的用法。

public interface Function {  
   public R apply(T t);  
}  

T - 给定的输入值 R - 输出或返回值。
在这里,对象类型T被输入到一个lambda表达式中,过程和对象T被作为值返回。

java util 函数类方法

默认方法是andThen()和compose()方法,静态方法是ident()方法。

函数接口应用方法示例

这个函数apply方法的输入是字符串,输出是字符串。apply()方法处理字符串并返回字符串作为值

import java.util.function.Function;  
  
public class MyFunctionExample {  
 static String HelloWorld(String name) {  
  return "Hello " + name;  
 }  
  
 public static void main(String[] args) {  
  Function functionalVariable = MyFunctionInterface::HelloWorld;  
  System.out.println(functionalVariable.apply("Frank"));  
 }  
}  

而输出是

Hello Frank  

还有一个例子是apply()方法的例子

import java.util.function.Function;  
  
public class MyFunctionExample {  
  
 public static void main(String[] args) {  
  Function IncrementFunction = (value) -> (value + 1);  
  System.out.println(IncrementFunction.apply(2));  
  System.out.println(IncrementFunction.apply(5));  
  
 }  
  
}  

上述代码的输出是

output is 3,6  

函数接口andThen方法的例子

andThen()是默认方法。这个方法在函数应用后将被调用的函数与其他函数结合起来。

语法

default  Function andThen(Function after)  

参数 - 在函数之后

import java.util.function.Function;  
public class MyFunctionExample {  
 public static void main(String[] args) {  
  Function IncrementFunction = (value) -> (value + 1);  
     Function doubleFunction = value -> 2*value;  
        double output=IncrementFunction.andThen(doubleFunction).apply(10);  
        System.out.println("output of andThen: "output);  
        }  
}  

上面的代码输出是

the output of andThen: 22.0  

函数接口合成方法示例

这是一个默认的方法。这是在应用函数之前将被调用的函数与其他函数结合起来。语法

  
default  Function compose(Function before)  

import java.util.function.Function;  
public class MyFunctionExample {  
 public static void main(String[] args) {  
  Function IncrementFunction = (value) -> (value + 1);  
     Function doubleFunction = value -> 2*value;  
        double output=IncrementFunction.compose(doubleFunction).apply(10);  
        System.out.println("output of compose: "+output);  
 }  
}  

上述代码的输出是

the output of composing: 21.0