在jdk1.8及其之后版本的jdk都大量运用了函数式接口(包名:java.util.function),并且也是Lambda表达式的体现,并且在jdk1.8新特性的stream流中大量运用。
函数式接口:一个接口只有一个只有一个抽象方法,并且类上有注解:@FunctionalInterface
优点:
- 代码简介
- 可以使用Lambda表达式
- 非常容易进行并行计算
缺点: - 不会的人可能理解不了代码
函数式接口四大类型
函数式接口名 | 抽象方法 | 大致含义 |
---|---|---|
Function<T, R> | R apply(T t) | 函数型:传入一个泛型t参数,返回类型R的数据结果(源码见图:Function.png) |
Predicate<T> | boolean test(T t) | 断言型:传入一个泛型t参数,返回boolean值 |
Supplier<T> | T get() | 供给型:不需要参数,返回一个泛型t结果 |
Consumer | void accept(T t) | 消费型:传入一个泛型t参数,无返回值 |
下面只会给出Function的简单示例,其他都通过stream流去理解
Function
代码示例:将字符串数据转成整数类型。传入一个String类型,返回一个Integer类型
/**
* @author 小鱼
* @version 1.0
* @date 2020/12/3 9:17 下午
* 测试:将字符串数据转成整数类型。传入一个String类型,返回一个Integer类型
*/
public class DemoFunction {
public static void main(String[] args) {
/*Function<String,Integer> testFunc = new Function<String,Integer>(){
@Override
public Integer apply(String s) {
return Integer.parseInt(s);
}
};*/
// 因为是函数式接口,所以可以使用下面的形式简写
Function<String,Integer> testFunc = (str)->{return Integer.parseInt(str);};
System.out.println(testFunc.apply("2"));
}
}
Function.png
实际列子再次理解函数式接口和函数式编程
/**
* @author 小鱼
* @version 1.0
* @date 2022/12/3 9:38 下午
* 使用stream流程处理数据。
* 1.id是偶数的
* 2.年龄大于23
* 3.将名字转成大写
* 4.id倒序
*/
public class Demo01 {
public static void main(String[] args) {
Student student = new Student();
student.setAge(20);
student.setId(1);
student.setName("xiaoYu");
Student student1 = new Student();
student1.setAge(26);
student1.setId(2);
student1.setName("xiaoLan");
Student student2 = new Student();
student2.setAge(24);
student2.setId(3);
student2.setName("xiaoHong");
Student student3 = new Student();
student3.setAge(22);
student3.setId(4);
student3.setName("xiaoLi");
// 1.我们先使用Stream<T> filter(Predicate<? super T> predicate)方法,里面是需要一个断言式函数
List<String> collect = Arrays.asList(student, student1, student2, student3).stream()
.filter((e) -> {
return e.getId() % 2 == 0;
})
.filter(e -> e.getAge() > 18)
.map(e -> {
return e.getName().toLowerCase();
})
.sorted((e, e1) -> e.compareTo(e1)).collect(Collectors.toList());
System.out.println(collect);
}
}