常用的函数式接口
@FunctionalInterface注解
这个标注用于表示该接口会设计成一个函数式接口。如果你用@FunctionalInterface定义了一个接口,而它却不是函数式接口的话,编译器将返回一个提示原因的错误。
在函数式接口中只能存在一个抽象方法,以及若干个default方法
Function
定义
T -> R 接受一个泛型T的对象作为入参,并返回一个泛型R的对象
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
应用实例
/**
* 在流运算中的map函数的入参类型就是Function
* <R> Stream<R> map(Function<? super T, ? extends R> mapper);
*/
List<Integer> list = apples.stream().map(Apple::getWeight).collect(toList());
拓展
Java 8同样提供两个入参的BiFunction((T, U)-> R) (也可以根据自己的需求去自定义N个入参的Function函数式接口,下同),以及针对类型转化效率更高的DoubleFunction、IntFunction等。
Consumer
定义
T -> void 接受一个泛型T类型的参数,无返回值
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
应用实例
/**
* 遍历每个对象打印颜色color
* forEach的入参就是Consumer类型
* default void forEach(Consumer<? super T> action) {
*/
apples.forEach(apple->System.out.println(apple.getColor))
Precidate
定义
T -> boolean 接受一个泛型T的入参,返回boolean
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
应用实例
/**
* 过滤apples中为Null的对象
* filter的入参就是Predicate类型
* Stream<T> filter(Predicate<? super T> predicate);
*/
apples.stream().filter(Objects::nonNull).collect(toList());
Supplier
定义
() -> R 无参函数,返回一个泛型R的对象
@FunctionalInterface
public interface Supplier<T> {
T get();
}
应用实例-Supplier实现工厂模式
public class RebuildFactoryWithSupplier {
final static Map<String, Supplier<Fruit>> fruitMap = new HashMap();
static {
fruitMap.put("watermelon", Watermelon::new);
fruitMap.put("balana", Banana::new);
fruitMap.put("apple", Apple::new);
}
;
public static void main(String[] args) {
RebuildFactoryWithSupplier factory = new RebuildFactoryWithSupplier();
factory.getFruit("apple").getWeight();
}
public Fruit getFruit(String fruitName) {
Fruit fruit = fruitMap.get(fruitName).get();
if (fruit == null) {
throw new IllegalArgumentException("No such product " + fruitName);
}
return fruit;
}
}
类型检查

网友评论