如何实现 Function\n在 Java 中使用 Lambda 表达式接口?\n
**Function<T, R>** 接口是 **java.util.function** 包中的函数式接口。此接口期待将一个参数作为输入,然后产生一个结果。**Function<T, R>** 接口可用作 **lambda 表达式** 或 **方法引用** 的分配目标。它包含一个抽象方法:**apply()**,两个默认方法:**andThen()** 和 **compose()**,以及一个静态方法:**identity()**。
语法
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}示例
import java.util.function.Function;
public class FunctionTest {
public static void main(String[] args) {
Function<Integer, Integer> f1 = i -> i*4; // lambda
System.out.println(f1.apply(3));
Function<Integer, Integer> f2 = i -> i+4; // lambda
System.out.println(f2.apply(3));
Function<String, Integer> f3 = s -> s.length(); // lambda
System.out.println(f3.apply("Adithya"));
System.out.println(f2.compose(f1).apply(3));
System.out.println(f2.andThen(f1).apply(3));
System.out.println(Function.identity().apply(10));
System.out.println(Function.identity().apply("Adithya"));
}
}输出
12 7 7 16 28 10 Adithya
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP