概念
函数式接口在Java中是指:有且仅有一个抽象方法的接口。
函数式接口,即适用于函数式编程场景的接口。而Java中的函数式编程体现就是Lambda,所以函数式接口就是可 以适用于Lambda使用的接口。只有确保接口中有且仅有一个抽象方法,Java中的Lambda才能顺利地进行推导。
格式
只要确保接口中有且仅有一个抽象方法即可:
修饰符 interface 接口名称 {
public abstract 返回值类型 方法名称(可选参数信息);
// public abstract 可以省略
// 其他非抽象方法内容(默认方法、静态方法)
}
@FunctionalInterface注解
与 @override 注解的作用类似,Java 8中专门为函数式接口引入了一个新的注解:@FunctionalInterface。该注解可用于一个接口的定义上:
@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
}
一旦使用该注解来定义接口,编译器将会强制检查该接口是否确实有且仅有一个抽象方法,否则将会报错。需要注 意的是,即使不使用该注解,只要满足函数式接口的定义,这仍然是一个函数式接口,使用起来都一样。
自定义函数式接口
对于刚刚定义好的 MyFunctionalInterface 函数式接口,典型使用场景就是作为方法的参数:
public class Demo09FunctionalInterface {
// 使用自定义的函数式接口作为方法参数
private static void doSomething(MyFunctionalInterface inter) {
inter.myMethod(); // 调用自定义的函数式接口方法
}
public static void main(String[] args) {
// 调用使用函数式接口的方法
doSomething(() ‐> System.out.println("Lambda执行啦!"));
}
}
自定义函数式接口(无参无返回)
定义一个函数式接口 Eatable ,内含抽象 eat 方法,没有参数或返回值。使用该接口作为方法的参数,并进而通过Lambda来使用它。
@FunctionalInterface
public interface Eatable {
public abstract void eat();
}
public class Test {
// 使用自定义的函数式接口作为方法参数
private static void doSomething(Eatable eatable){
// 调用自定义的函数式接口方法
eatable.eat();
}
public static void main(String[] args) {
// 调用使用函数式接口的方法
doSomething(()-> System.out.println("厉害了我的国"));
}
}
自定义函数式接口(有参有返回)
定义一个函数式接口 Sumable,内含抽象 sum方法,可以将两个int数字相加返回int结果。使用该接口作为方法的参数,并进而通过Lambda来使用它。
@FunctionalInterface
public interface Sumable {
int sum(int a, int b);
}
public class Test {
private static int sum(Sumable sumable,int a,int b){
return sumable.sum(a,b);
}
public static void main(String[] args) {
System.out.println(sum((x,y)->(x + y),5,3));
}
}
常用函数式接口
1. Supplier接口
java.util.function.Supplier 接口仅包含一个无参的方法:T get() 。用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。
import java.util.function.Supplier;
public class Demo08Supplier {
private static String getString(Supplier<String> function) {
return function.get();
}
public static void main(String[] args) {
String msgA = "Hello";
String msgB = "World";
System.out.println(getString(() ‐> msgA + msgB));
}
}
1.1 数组元素最大值
public class Test {
private static void getMax(Supplier<Integer> supplier){
Integer max = supplier.get();
System.out.println(max);
}
public static void main(String[] args) {
int[] array = {4,8,20,21,5,2,1};
getMax(() -> {
int max = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] > max){
max = array[i];
}
}
return max;
});
}
}
2. Consumer接口
java.util.function.Consumer 接口则正好相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型参数决定。
抽象方法:accept:意为消费一个指定泛型的数据。
默认方法:andThen:如果一个方法的参数和返回值全都是Consumer 类型,那么就可以实现效果:消费一个数据的时候,首先做一个操作,然后再做一个操作,实现组合。要想实现组合,需要两个或多个Lambda表达式即可,而合andThen的语义正是“一步接一步”操作。
例如:格式化打印信息
import java.util.function.Consumer;
public class Demo10ConsumerAndThen {
private static void consumeString(Consumer<String> one,Consumer<String> two,String[] array){
for (String info : array) {
one.andThen(two).accept(info);
}
}
public static void main(String[] args) {
String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男" };
consumeString(
s -> System.out.print("姓名:" + s.split(",")[0] + "。"),
s -> System.out.println("性别:" + s.split(",")[1]),
array
);
}
}
3. Predicate接口
有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。这时可以使用 java.util.function.Predicate 接口。
抽象方法:test:用于条件判断的场景
public class Demo15PredicateTest {
private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.test("HelloWorld");
System.out.println("字符串很长吗:" + veryLong);
}
public static void main(String[] args) {
method(s ‐> s.length() > 5);
}
}
默认方法:and:既然是条件判断,就会存在与、或、非三种常见的逻辑关系。其中将两个Predicate条件使用“与”逻辑连接起来实现“并且”的效果时,可以使用default方法 and。
例如:如果要判断一个字符串既要包含大写“H”,又要包含大写“W”,那么:
import java.util.function.Predicate;
public class Demo16PredicateAnd {
private static void method(Predicate<String> one, Predicate<String> two) {
boolean isValid = one.and(two).test("Helloworld");
System.out.println("字符串符合要求吗:" + isValid);
}
public static void main(String[] args) {
method(s ‐> s.contains("H"), s ‐> s.contains("W"));
}
}
默认方法:or:与 and 的“与”类似,默认方法 实现逻辑关系中的“或”。例如:如果希望实现逻辑“字符串包含大写H或者包含大写W”,那么代码只需要将“and”修改为“or”名称即可,其他都不变 :
import java.util.function.Predicate;
public class Demo16PredicateAnd {
private static void method(Predicate<String> one, Predicate<String> two) {
boolean isValid = one.or(two).test("Helloworld");
System.out.println("字符串符合要求吗:" + isValid);
}
public static void main(String[] args) {
method(s ‐> s.contains("H"), s ‐> s.contains("W"));
}
}
默认方法:negate:取反。它是执行了test方法之后,对结果boolean值进行“!”取反而已。一定要在test方法调用之前调用negate方法。例如:
import java.util.function.Predicate;
public class Demo17PredicateNegate {
private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.negate().test("HelloWorld");
System.out.println("字符串很长吗:" + veryLong);
}
public static void main(String[] args) {
method(s ‐> s.length() < 5);
}
}
例如:集合信息筛选
数组当中有多条“姓名+性别”的信息如下,请通过Predicate接口的拼装将符合要求的字符串筛选到集合中ArrayList,需要同时满足两个条件:1、必须为女生;2、姓名为4个字。
public class Test {
private static void method(String s, Predicate<String> one, Predicate<String> two){
boolean is = one.and(two).test(s);
ArrayList<String> list = new ArrayList<>();
if (is){
list.add(s);
}
System.out.println(list.toString());
}
public static void main(String[] args) {
String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男", "赵丽颖,女" };
for (String s : array) {
method(s, s1 -> s1.length() == 6, s1 -> s1.substring(s1.length()-1).equals("女"));
}
}
}
4. Function接口
java.util.function.Function<T,R>接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件, 后者称为后置条件。有进有出,所以称为“函数Function”。
抽象方法:apply:Function接口中最主要的抽象方法为:R apply(T t),根据类型T的参数获取类型R的结果。使用的场景例如:将 String 类型转换为 Integer 类型。
import java.util.function.Function;
public class Demo11FunctionApply {
private static void method(Function<String, Integer> function) {
int num = function.apply("10");
System.out.println(num + 20);
}
public static void main(String[] args) {
method(s ‐> Integer.parseInt(s));
method(Integer::parseInt);
}
}
默认方法:andThen:用来进行组合操作。该方法同样用于“先做什么,再做什么”的场景,与 consumer 中的 andThen 差不多。
import java.util.function.Function;
public class Demo12FunctionAndThen {
// 第一个操作是将字符串解析成为int数字,第二个操作是乘以10。
private static void method(Function<String, Integer> one, Function<Integer, Integer> two) {
int num = one.andThen(two).apply("10");
System.out.println(num + 20);
}
public static void main(String[] args) {
method(Integer::parseInt, i ‐> i *= 10);
}
}
例如:自定义函数模型拼接
使用Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
- 将字符串截取数字年龄部分,得到字符串;
- 将上一步的int数字累加100,得到结果int数字。
- 将上一步的字符串转换成为int类型的数字;
import java.util.function.Function;
public class Test {
private static int method(String s,Function<String,String> one,Function<String,Integer> two,Function<Integer,Integer> three){
return one.andThen(two).andThen(three).apply(s);
}
public static void main(String[] args) {
String str = "coco,12";
int method = method(str, s -> s.split(",")[1],
Integer::parseInt,
n -> n += 100
);
System.out.println(method);
}
}
感谢你看到这里,我是程序员麦冬,一个java开发从业者,深耕行业六年了,每天都会分享java相关技术文章或行业资讯
欢迎大家关注和转发文章,后期还有福利赠送!