Java8::函数式接口
一、简介
1.1 四大核心函数
接口 | 入参类型 | 返参类型 | 描述 | 描述 |
---|---|---|---|---|
Consumer <T> 消费型接口 | T | void | 有入参无出参 | 对类型为T的对象应用操作,包含方法:void accept(T t) |
Supplier <T> 供给型接口 | 无 | T | 有出参无入参 | 返回类型为T的对象,包含方法:T get() |
Function <T, R> 函数型接口 | T | R | 有出参有入参 | 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t) |
Predicate<T> 断定型接口 | T | boolean | 入参T,返回Boolean | 确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法:boolean test(T t) |
BiFunction<T, U, R> | T, U | R | 入参T、U,反参R | 对类型为 T, U 参数应用操作,返回 R 类型的结果。包含方法为: R apply(T t, U u); |
1.2 其他函数
接口 | 入参类型 | 返参类型 | 描述 | 描述 |
---|---|---|---|---|
BiFunction<T, U, R> | T, U | R | 入参T、U,反参R | 对类型为 T, U 参数应用操作,返回 R 类型的结果。包含方法为: R apply(T t, U u); |
二、举例
2.1 Consumer接口
Consumer<String> consumer = (String str) -> System.out.println(str);
consumer.accept("hello world!");// hello world!
2.2 Supplier 接口
public static void main(String[] args) {
int[]arr={20,12,3,6,8};
Supplier supplier = ()->{
int m=arr[0];
for(int i=0;i<arr.length;i++){
if(arr[i]>m){
m=arr[i];
}
}
return m;
};
System.out.println(supplier.get());// 20
System.out.println(getMax(supplier));// 20
}
/**
* 返回最大值
* @param sup
* @return
*/
public static Integer getMax(Supplier<Integer>sup) {
return sup.get();
}
2.3 Function接口
public static void main(String[] args) {
Function<String,Integer> function = (a)-> Integer.valueOf(a);
System.out.println(function.apply("17"));// 17
System.out.println(getInteger(function,"17")); // 17
}
/**
* 字符串转数字
* @param fun
* @return
*/
public static Integer getInteger(Function<String,Integer> fun,String str) {
return fun.apply(str);
}
2.4 Predicate接口
Predicate<Integer> predicate = number -> number != 0;
System.out.println(predicate.test(10)); //true
2.5 BiFunction接口
BiFunction<String,String,Integer> biFunction = (String a,String b)-> Integer.valueOf(a) + Integer.valueOf(b);
System.out.println(biFunction.apply("12","3")); // 15
版权声明:本文为qq_29898779原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。