java8-函数式接口
函数式接口
函数式接口
由来
使用Lambda的前提是需要有函数式接口,而Lambda表达式不关心接口名,抽象方法名。只关心返回值,参数列表。为了让我们使用Lambda表达式,JDK提供了大量 的函数式接口。
常用接口
Supplier
无参有返回值
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
使用: 需要提供返回的类型
Consumer
有参无返回值
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
Function
有参有返回值
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
Predicate
有参返回值为Boolean
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
方法引用
由来
lambda表达式,在使用时出现冗余情况。
解决方案
因为在Lambda表达式中要执行的代码和我们另一个方法中的代码时一样的。这时就没有必要重写一份逻辑了,这时可以引用重复代码。
例子
public class Demo03 {
public static void main(String[] args) {
/*
printSum(a ->{
int sum = 0;
for(int i : a){
sum += i;
}
System.out.println(sum);
});
*/
printSum(Demo03::getTotal);
}
public static void getTotal(int[] arr){
int sum = 0;
for(int i: arr){
sum += i;
}
System.out.println(sum);
}
public static void printSum(Consumer<int[]> a){
int[] arr = {1,2312,412};
a.accept(arr);
}
}
格式
InstanceName::methodName 对象名::方法名
ClassName::staticMethodName 类名::静态方法
ClassName::methodName 类名::普通方法
ClassName::new 类名::构造器
TypeName::new String[]::new 调用数组的构造器