Lambda表达式采用函数式编程,以下介绍Java8定义的几个常用的函数式接口。
Consumer<T>
:消费型接口
Method: void accept(T t); 有参数,无返回
Code:
Consumer consumer = System.out::println;
consumer.accept("segmentfault");
Extend:
- andThen(Consumer<? super T> after);
Supplier<T>
:供给细型接口
Method: T get(); 无参数,有返回
Code:
Supplier fun = () -> "response";
System.out.println(fun.get());
Function<T,R>
:函数型接口
Method: R apply(T t); 有参数,有返回
Code:
Function<Integer,Integer> fun = e -> e+1;
int r = fun.apply(1);
Extend:
- compose(Function<? super V, ? extends T> before);
- andThen(Function<? super R, ? extends V> after);
Predicate<T>
:断言型接口
Method: boolean test(T t); 有参数,返回true|false
Code:
Predicate<Integer> fun = e -> e == 1;
boolean r = fun.test(1);
Extend:
- and(Predicate<? super T> other); -> &&
- or(Predicate<? super T> other); -> or
- negate(); -> ^
Bi型接口
BiConsumer、BiFunction、BiPrediate 是 Consumer、Function、Predicate 的扩展,可以传入多个参数,没有 BiSupplier 是因为 Supplier 没有入参。
自定义接口
Code:
@FunctionalInterface
public interface ConsumerFunction {
void fun(int i);
}
包:java.util.function
参考:
java8 函数编程
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。