1. 基本概念
- 函数式接口就是只定义一个抽象方法的接口
- 注:可以有很多默认方法
1.1 @FunctionalInterface
@FunctionalInterface 可检测接口是否符合函数式接口
1.2 函数描述符
函数式接口的抽象方法的签名基本上就是 Lambda 表达式的签名。我们将这种抽象方法叫作函数描述符
2. 常用函数式接口
public interface Predicate<T> {
boolean test(T t);
}
public interface Consumer<T> {
void accept(T t);
}
public interface Supplier<T> {
T get();
}
public interface Function<T, R> {
R apply(T t);
}
2.1 函数签名
| 接口名 | 抽象方法 | 描述符 |
|---|---|---|
| Predicate | boolean test(T t) | T -> boolean |
| BiPredicate<T, U> | test(T t, U u) | ( T, U ) -> boolean |
| Consumer | void accept(T t) | T -> void |
| BiConsumer<T, U> | void accept(T t, U u) | ( T, U ) -> void |
| Function<T, R> | R apply(T t) | T -> R |
| BiFunction<T, U, R> | R apply(T t, U u) | ( T, U ) -> R |
| Supplier | T get() | void -> T |
2.2 例程
Predicate<String> predicate = str -> "aaa".equals(str);
BiPredicate<String, String> biPredicate = (o1, o2) -> o1.equals(o2);
boolean flag = predicate.test("aaa");
boolean flag2 = biPredicate.test("aaa", "111");
Consumer<String> consumer = str -> System.out.println(str);
BiConsumer<String, String> biConsumer = (a, b) -> System.out.println(a + "; " + b);
consumer.accept("222");
biConsumer.accept("aaa", "bbb");
Supplier<OrderDTO> supplier = () -> new OrderDTO();
OrderDTO orderDTO = supplier.get();
Function<Long, String> function = (Long l) -> l.toString();
BiFunction<String, Integer, String> biFunction = (str, i) -> str.substring(i);
String apply = function.apply(1000L);
String apply2 = biFunction.apply("abcde", 2);







网友评论