在jdk1.8及其之后版本的jdk都大量運(yùn)用了函數(shù)式接口(包名:java.util.function)不见,并且也是Lambda表達(dá)式的體現(xiàn),并且在jdk1.8新特性的stream流中大量運(yùn)用魂角。
函數(shù)式接口:一個(gè)接口只有一個(gè)只有一個(gè)抽象方法,并且類(lèi)上有注解:@FunctionalInterface
優(yōu)點(diǎn):
- 代碼簡(jiǎn)介
- 可以使用Lambda表達(dá)式
- 非常容易進(jìn)行并行計(jì)算
缺點(diǎn): - 不會(huì)的人可能理解不了代碼
函數(shù)式接口四大類(lèi)型
函數(shù)式接口名 | 抽象方法 | 大致含義 |
---|---|---|
Function<T, R> | R apply(T t) | 函數(shù)型:傳入一個(gè)泛型t參數(shù)截粗,返回類(lèi)型R的數(shù)據(jù)結(jié)果(源碼見(jiàn)圖:Function.png) |
Predicate<T> | boolean test(T t) | 斷言型:傳入一個(gè)泛型t參數(shù)疫稿,返回boolean值 |
Supplier<T> | T get() | 供給型:不需要參數(shù),返回一個(gè)泛型t結(jié)果 |
Consumer | void accept(T t) | 消費(fèi)型:傳入一個(gè)泛型t參數(shù)粉臊,無(wú)返回值 |
下面只會(huì)給出Function的簡(jiǎn)單示例草添,其他都通過(guò)stream流去理解
Function
代碼示例:將字符串?dāng)?shù)據(jù)轉(zhuǎn)成整數(shù)類(lèi)型。傳入一個(gè)String類(lèi)型扼仲,返回一個(gè)Integer類(lèi)型
/**
* @author 小魚(yú)
* @version 1.0
* @date 2020/12/3 9:17 下午
* 測(cè)試:將字符串?dāng)?shù)據(jù)轉(zhuǎn)成整數(shù)類(lèi)型远寸。傳入一個(gè)String類(lèi)型,返回一個(gè)Integer類(lèi)型
*/
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);
}
};*/
// 因?yàn)槭呛瘮?shù)式接口屠凶,所以可以使用下面的形式簡(jiǎn)寫(xiě)
Function<String,Integer> testFunc = (str)->{return Integer.parseInt(str);};
System.out.println(testFunc.apply("2"));
}
}
Function.png
實(shí)際列子再次理解函數(shù)式接口和函數(shù)式編程
/**
* @author 小魚(yú)
* @version 1.0
* @date 2022/12/3 9:38 下午
* 使用stream流程處理數(shù)據(jù)驰后。
* 1.id是偶數(shù)的
* 2.年齡大于23
* 3.將名字轉(zhuǎn)成大寫(xiě)
* 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)方法,里面是需要一個(gè)斷言式函數(shù)
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);
}
}