一、函数式接口
1. 函数式接口的由来
我们知道使用Lambda表达式的前提是需要有函数式接口,而Lambda表达式使用时不关心接口名,抽象方法名。只关心抽象方法的参数列表和返回值类型。因此为了让我们使用Lambda表达式更加方便,在JDK中提供了大量常用的函数式接口
public class Demo01Fun {
public static void main(String[] args) {
fun1((arr)->{
int sum = 0 ;
for (int i : arr) {
sum += i;
}
return sum;
});
}
public static void fun1(Operator operator){
int[] arr = {1,2,3,4};
int sum = operator.getSum(arr);
System.out.println("sum = " + sum);
}
}
/**
* 函数式接口
*/
@FunctionalInterface
interface Operator{
int getSum(int[] arr);
}
2. 函数式接口介绍
在JDK中帮我们提供的有函数式接口,主要是在 java.util.function 包中。
2.1 Supplier
无参有返回值的接口,对于的Lambda表达式需要提供一个返回数据的类型。供应商的意思。
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
使用:
/**
* Supplier 函数式接口的使用
*/
public class SupplierTest {
public static void main(String[] args) {
fun1(()->{
int arr[] = {22,33,55,66,44,99,10};
// 计算出数组中的最大值
Arrays.sort(arr);
return arr[arr.length-1];
});
}
private static void fun1(Supplier<Integer> supplier){
// get() 是一个无参的有返回值的 抽象方法
Integer max = supplier.get();
System.out.println("max = " + max);
}
}
2.2 Consumer
有参无返回值得接口,前面介绍的Supplier接口是用来生产数据的,而Consumer接口是用来消费数据的,使用的时候需要指定一个泛型来定义参数类型
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
使用:将输入的数据统一转换为小写输出
public class ConsumerTest {
public static void main(String[] args) {
test(msg -> {
System.out.println(msg + "-> 转换为小写:" + msg.toLowerCase());
});
}
public static void test(Consumer<String> consumer){
consumer.accept("Hello World");
}
}
默认方法:andThen
如果一个方法的参数和返回值全部是Consumer类型,那么就可以实现效果,消费一个数据的时候,首先做一个操作,然后再做一个操作,实现组合,而这个方法就是Consumer接口中的default方法 andThen方法
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
具体的操作
public class ConsumerAndThenTest {
public static void main(String[] args) {
test2(msg1->{
System.out.println(msg1 + "-> 转换为小写:" + msg1.toLowerCase());
},msg2->{
System.out.println(msg2 + "-> 转换为大写:" + msg2.toUpperCase());
});
}
public static void test2(Consumer<String> c1,Consumer<String> c2){
String str = "Hello World";
//c1.accept(str); // 转小写
//c2.accept(str); // 转大写
//c1.andThen(c2).accept(str);
c2.andThen(c1).accept(str);//先大写再小写 《==》 c2.accept(str)之后c1.accept(str)
}
}
2.3 Function
有参有返回值的接口,Function接口是根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。有参数有返回值。
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
使用:传递进入一个字符串返回一个数字
public class FunctionTest {
public static void main(String[] args) {
test(msg ->{
return Integer.parseInt(msg);
});
}
public static void test(Function<String,Integer> function){
Integer apply = function.apply("666");
System.out.println("apply = " + apply);
}
}
默认方法:andThen,也是用来进行组合操作,
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
public class FunctionAndThenTest {
public static void main(String[] args) {
test(msg ->{
return Integer.parseInt(msg);
},msg2->{
return msg2 * 10;
});
}
public static void test(Function<String,Integer> f1,Function<Integer,Integer> f2){
/*Integer i1 = f1.apply("666");
Integer i2 = f2.apply(i1);*/
Integer i2 = f1.andThen(f2).apply("666");// <===> f1.apply("666")之后f2.apply(i1)
System.out.println("i2:" + i2);
}
}
默认的compose方法的作用顺序和andThen方法刚好相反
而静态方法identity则是,输入什么参数就返回什么参数
2.4 Predicate
有参且返回值为Boolean的接口
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
使用:
public class PredicateTest {
public static void main(String[] args) {
test(msg -> {
return msg.length() > 3;
},"HelloWorld");
}
private static void test(Predicate<String> predicate,String msg){
boolean b = predicate.test(msg);
System.out.println("b:" + b);
}
}
在Predicate中的默认方法提供了逻辑关系操作 and or negate isEquals方法
import java.util.function.Predicate;
public class PredicateDefaultTest {
public static void main(String[] args) {
test(msg1 -> {
return msg1.contains("H");
},msg2 -> {
return msg2.contains("W");
});
}
private static void test(Predicate<String> p1,Predicate<String> p2){
/*boolean b1 = predicate.test(msg);
boolean b2 = predicate.test("Hello");*/
// b1 包含H b2 包含W
// p1 包含H 同时 p2 包含W
boolean bb1 = p1.and(p2).test("Hello");
// p1 包含H 或者 p2 包含W
boolean bb2 = p1.or(p2).test("Hello");
// p1 不包含H
boolean bb3 = p1.negate().test("Hello");
System.out.println(bb1); // FALSE
System.out.println(bb2); // TRUE
System.out.println(bb3); // FALSE
}
}
二、方法引用
1. 为什么要用方法引用
1.1 lambda表达式冗余
在使用Lambda表达式的时候,也会出现代码冗余的情况,比如:用Lambda表达式求一个数组的和
import java.util.function.Consumer;
public class FunctionRefTest01 {
public static void main(String[] args) {
printMax(a->{
// Lambda表达式中的代码 和 getTotal中的代码冗余了
int sum = 0;
for (int i : a) {
sum += i;
}
System.out.println("数组之和:" + sum);
});
}
/**
* 求数组中的所有元素的和
* @param a
*/
public void getTotal(int a[]){
int sum = 0;
for (int i : a) {
sum += i;
}
System.out.println("数组之和:" + sum);
}
private static void printMax(Consumer<int[]> consumer){
int[] a= {10,20,30,40,50,60};
consumer.accept(a);
}
}
1.2 解决方案
因为在Lambda表达式中要执行的代码和我们另一个方法中的代码是一样的,这时就没有必要重写一份逻辑了,这时我们就可以“引用”重复代码
import java.util.function.Consumer;
public class FunctionRefTest02 {
public static void main(String[] args) {
// :: 方法引用 也是JDK8中的新的语法
printMax(FunctionRefTest02::getTotal);
}
/**
* 求数组中的所有元素的和
* @param a
*/
public static void getTotal(int a[]){
int sum = 0;
for (int i : a) {
sum += i;
}
System.out.println("数组之和:" + sum);
}
private static void printMax(Consumer<int[]> consumer){
int[] a= {10,20,30,40,50,60};
consumer.accept(a);
}
}
:: 方法引用 也是JDK8中的新的语法。
方法引用会根据已经存在的方法直接引用,
而原本的lambda表达式会重新封装成一个方法。
这样看下来方法引用的效率会高点。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OYtgY4yy-1681026101923)(JDK8新特性.assets/image-20220613151230912.png)]
2. 方法引用的格式
符号表示:::
符号说明:双冒号为方法引用运算符,而它所在的表达式被称为方法引用
应用场景:如果Lambda表达式所要实现的方案,已经有其他方法存在相同的方案,那么则可以使用方法引用。
常见的引用方式:
方法引用在JDK8中使用是相当灵活的,有以下几种形式:
-
instanceName::methodName ===》对象::方法名
-
ClassName::staticMethodName ===》类名::静态方法名
-
ClassName::methodName ===》类名::普通方法(类名::实例方法名)
-
ClassName::new ===》类名::new (类名::构造器)
-
TypeName[]::new ===》String[]::new (数组::构造器)
2.1 对象名::方法名
这是最常见的一种用法。如果一个类中的已经存在了一个成员方法,则可以通过对象名引用成员方法
public static void main(String[] args) {
Date now = new Date();
Supplier<Long> supplier = ()->{return now.getTime();};
System.out.println(supplier.get());
// 然后我们通过 方法引用 的方式来处理
Supplier<Long> supplier1 = now::getTime;
System.out.println(supplier1.get());
}
方法引用的注意事项:
- 被引用的方法,参数要和接口中的抽象方法的参数一样
- 当接口抽象方法有返回值时,被引用的方法也必须有返回值
2.2 类名::静态方法名
也是比较常用的方式:
public class FunctionRefTest04 {
public static void main(String[] args) {
Supplier<Long> supplier1 = ()->{
return System.currentTimeMillis();
};
System.out.println(supplier1.get());
// 通过 方法引用 来实现
Supplier<Long> supplier2 = System::currentTimeMillis;
System.out.println(supplier2.get());
}
}
2.3 类名::实例方法名
Java面向对象中,类名只能调用静态方法,类名引用实例方法是有前提的,实际上是拿第一个参数作为方法的调用者
import java.util.Date;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public class FunctionRefTest05 {
public static void main(String[] args) {
Function<String,Integer> function = (s)->{
return s.length();
};
System.out.println(function.apply("hello"));
// 通过方法引用来实现
Function<String,Integer> function1 = String::length;
System.out.println(function1.apply("hahahaha"));
BiFunction<String,Integer,String> function2 = String::substring;
String msg = function2.apply("HelloWorld", 3);
System.out.println(msg);
}
}
2.4 类名::构造器
由于构造器的名称和类名完全一致,所以构造器引用使用::new
的格式使用,
public class FunctionRefTest06 {
public static void main(String[] args) {
Supplier<Person> sup = ()->{return new Person();};
System.out.println(sup.get());
// 然后通过 方法引用来实现
Supplier<Person> sup1 = Person::new;
System.out.println(sup1.get());
BiFunction<String,Integer,Person> function = Person::new;
System.out.println(function.apply("张三",22));
}
}
2.5 数组::构造器
数组是怎么构造出来的呢?
public static void main(String[] args) {
Function<Integer,String[]> fun1 = (len)->{
return new String[len];
};
String[] a1 = fun1.apply(3);
System.out.println("数组的长度是:" + a1.length);
// 方法引用 的方式来调用数组的构造器
Function<Integer,String[]> fun2 = String[]::new;
String[] a2 = fun2.apply(5);
System.out.println("数组的长度是:" + a2.length);
}
小结:方法引用是对Lambda表达式符合特定情况下的一种缩写方式,它使得我们的Lambda表达式更加的精简,也可以理解为lambda表达式的缩写形式,不过要注意的是方法引用只能引用已经存在的方法。