一、Function 接口概述
Java8 在 java.util.function
包中新增了一些函数式接口,其中一个是 Function
接口。Function
接口代表一个参数输入一个结果的函数。它接收一个泛型 T
的参数,同时返回一个泛型 R
的结果。其中通过 apply()
方法去执行函数式操作,通过 compose()
、andThen()
等方法可以使得多个 Function
组合成一个更复杂的运算。
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
二、Function 使用示例
1. Function 的基本使用
实现 Function
接口,重写 apply()
方法,并在方法中完成具体的功能,如下所示:
Function<String, Integer> strLength = str -> str.length(); // 定义一个Function对象
int length = strLength.apply("Hello World!"); // 将Hello World字符串作为参数,执行strLength的apply()方法
System.out.println("字符串长度为:" + length); // 输出结果:字符串长度为:12
2. Function 的组合运算
除了单独使用 Function
,我们还可以通过 compose()
、andThen()
等方法将不同的 Function
组合成一个更复杂的运算,如下所示:
Function<String, String> replaceA = str -> str.replace("a", "A"); // 将所有的小写a替换为大写A的Function
Function<String, String> replaceB = str -> str.replace("b", "B"); // 将所有的小写b替换为大写B的Function
Function<String, String> replaceAAndB = replaceA.compose(replaceB); // 将replaceA和replaceB组合
String result = replaceAAndB.apply("abcdbae"); // 执行组合后的Function
System.out.println("字符串替换后为:" + result); // 输出结果:字符串替换后为: ABCDBAE
3. Function 的链式组合
在 Function
的链式组合中,使用 andThen()
来将不同的 Function
加入到链中,执行顺序是从左到右,如下所示:
Function<Double, Double> addOne = d -> d + 1; // 加一操作
Function<Double, Double> multiplyByTwo = d -> d * 2; // 乘二操作
Function<Double, Double> chain = addOne.andThen(multiplyByTwo); // 加一乘二链式操作
Double result = chain.apply(1.0); // 将1.0作为初始值,执行链中的操作
System.out.println("链式操作后的结果是:" + result); // 输出结果:链式操作后的结果是:4.0
三、Function 中其他方法的使用
1. and(), or() 方法
除了 compose()
、andThen()
方法,Function
还具有 and()
、or()
方法,分别代表函数式的逻辑与和逻辑或操作。
Function<Integer, Boolean> isEven = n -> n % 2 == 0; // 判断是否是偶数
Function<Integer, Boolean> isPositive = n -> n > 0; // 判断是否是正数
Function<Integer, Boolean> condition = isEven.and(isPositive); // 同时满足以上两个条件
boolean result = condition.apply(10); // 10为偶数且为正数,返回true
Function<Integer, Boolean> condition2 = isEven.or(isPositive); // 同时满足以上两个条件之一
boolean result2 = condition2.apply(-1); // -1为负数,返回false
System.out.println("条件 and 的结果为:" + result); // 输出结果:条件 and 的结果为:true
System.out.println("条件 or 的结果为:" + result2); // 输出结果:条件 or 的结果为:true
2. identity() 方法
identity()
方法是 Function
接口中自带的一个静态方法,它返回一个与参数相等的 Function
对象。通过这个方法也能够更方便地将一个 Function
作为参数来传递或返回。
Function<String, String> function = Function.identity();
String result = function.apply("Hello World!");
System.out.println(result); // 输出结果:Hello World!
四、总结
本文针对 Java8 中 Function
接口进行了全面的解析,包括其概述、使用示例以及相关方法的介绍和使用。Function
接口是 Java8 中函数式编程的基础,掌握 Function
接口的使用将会在函数式编程中带来很大的便利,也将帮助程序员更好地理解函数式编程的思想。