【笔记】Java的函数式接口

前言

Java的函数式接口学习笔记

供给型函数式接口(Supplier)

  • 对于一个返回出参的操作,在调用时由调用者添加自定义前置操作

定义类

1
2
3
4
5
class Cls {
void method(Supplier<String> supplier) {
String result = supplier.get();
}
}

创建对象

1
2
3
4
5
6
7
8
Cls cls = new Cls();

cls.method(() -> {

...

return "";
});

消费型函数式接口(Consumer)

  • 对于一个传递入参的操作,在调用时由调用者添加自定义后置操作

定义类

1
2
3
4
5
class Cls {
void method(Consumer<String> consumer) {
consumer.accept("");
}
}

创建对象

1
2
3
4
5
Cls cls = new Cls();

cls.method((value) -> {
...
});
  • 通过调用andThen()方法,在后置操作追加后置操作
1
2
3
4
5
6
7
8
9
Cls cls = new Cls();

Consumer<Integer> consumer1 = (value) -> {
...
};
Consumer<Integer> consumer2 = consumer.andThen((value) -> {
...
});
Integer field = cls.getField(consumer2);

函数型函数式接口(Function)

  • 对于一个传递入参和返回出参的操作,在调用时由调用者添加自定义中置操作

定义类

  • Function的泛型分别定义入参数据类型和出参数据类型
1
2
3
4
5
Class Cls {
void method(Function<String, String> function) {
String result = function.apply("");
}
}

创建对象

1
2
3
4
5
6
7
8
Cls cls = new Cls();

cls.method((value) -> {

...

return "";
});
  • 通过调用andThen()方法,在后置操作继续追加后置操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Cls cls = new Cls();

Function<String, String> function1 = (value) -> {

...

return "";
};
Function<String, String> function2 = function1.andThen((value) -> {

...

return "";
});
Integer field = cls.getField(function2);
  • 通过调用compose()方法,在后置操作继续追加后置操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Cls cls = new Cls();

Function<String, String> function1 = (value) -> {

...

return "";
};
Function<String, String> function2 = function1.compose((value) -> {

...

return "";
});
Integer field = cls.getField(function2);

断言型函数式接口(Predicate)

  • 对于一个需要断言的操作,在调用时由调用者添加自定义断言操作

定义类

1
2
3
4
5
class Cls {
void method(Predicate<String> predicate) {
boolean success = predicate.test("");
}
}

创建对象

1
2
3
4
5
Cls cls = new Cls();

cls.method((value) -> {
return true;
})

完成

参考文献

哔哩哔哩——青空の霞光