0
点赞
收藏
分享

微信扫一扫

深度剖析JAVA 函数式接口

一、什么是函数式接口:

函数式接口,即适用于函数式编程场景的接口。而Java中的函数式编程体现就是Lambda,所以函数式接口就是可以适用于Lambda使用的接口。只有确保接口中有且仅有一个抽象方法,Java中的Lambda才能顺利地进行推导。可以有多个非抽象方法。 为了避免别人在这个接口中增加接口函数导致其有多个接口函数需要被实现,变成"非函数接口”,可以在接口上加上一个注解@FunctionalInterface, 这样别人就无法在里面添加新的接口函数了。

  1. FunctionalInterface是什么?

FunctionalInterface 中文称之为 函数式接口。是Java新特性之一,所谓的函数式接口,只能有一个抽象方法的接口(Interface) 2. FunctionalInterface有什么作用?

作为Java的新特性之一,主要是标识某一类接口,如果满足以上特性(只能有一个抽象方法的接口(Interface)), 就可以使用@FunctionalInterface注解。

一般是配合Lambda表达式一起使用。

二、函数式接口四大核心函数:

1.消费型接口:Consumer 有参无返回值 值

@FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * Params:t- the input argument */ void accept(T t); }

2.供给型接口:Supplier 无参有返回值,用于提供数据源的

@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * Returns:a result */ T get(); }

3.函数型接口:Function 最典型的是Function,有参有返回值,接受一个T类型的参数,并返回一个R类型的返回值

@FunctionalInterface public interface Function<T, R> { /** * Applies this function to the given argument. * Params: t- the function argument * Returns: the function result */ R apply(T t); }

4.断言型接口:Predicate 有参有返回值,返回值是boolean类型,用来判断某项条件是否满足。经常用来进行筛滤操作

@FunctionalInterface public interface Predicate<T> { /** * Evaluates this predicate on the given argument. * Params: t - the input argument * Returns: true if the input argument matches the predicate, otherwise false */ boolean test(T t); }

三、四大函数的实现调用

//对四大核心函数实现 Consumer<String> consumer = (str) -> { System.out.println(str); };

Supplier<String> supplier = () -> {
return 我是供给型接口;
};

Function<String, String> function = (str) -> {
return hello, + str;
};

Predicate<Integer> predicate = (i) -> {
return i > 10;
};

void conDemo(String str, Consumer<String> consumer) {//把lambda表达式当成参数传递
consumer.accept(str);
}

String supDemo(Supplier<String> supplier) {
return supplier.get();
}

String funDemo(String str2, Function<String, String> function) {
return function.apply(str2);
}

boolean preDemo(Integer i, Predicate<Integer> predicate) {
return predicate.test(i);
}

String str = 消费型接口;

@Test
void conDemo2() {
conDemo(str, consumer);//打印结果:消费型接口
}

@Test
void supDemo2() {
System.out.println(supDemo(supplier));//打印结果:我是供给型接口
}

String str2 = 我是函数式接口;

@Test
void funDemo2() {
System.out.println(funDemo(str2, function));//打印结果:hello,我是函数式接口
}

Integer i = 12;

@Test
void preDemo2() {
System.out.println(preDemo(i, predicate));//打印结果:true
}

四、其他函数式接口:

Runnable:

@FunctionalInterface public interface Runnable { public abstract void run(); }

Callable:

@FunctionalInterface public interface Callable<V> { V call() throws Exception; } Comparator:

@FunctionalInterface public interface Comparator<T> { int compare(T o1, T o2); }

举报

相关推荐

0 条评论