函数式接口工具的引出
1.在JDK1.8之中提供有Lambda表达式也提供有方法引用,但是你会发现现在如果由开发者自己定义函数式接口,往往都需要使用"@FunctionalInterface"注解来进行大量声明,于是很多情况下如果为了方便则可以引用系统中提供的函数式接口
2.在系统之中专门提供有一个java.util.function的开发包,里面可以直接使用函数式接口,在这个包下面一共有如下的几个核心接口供使用:
//函数式接口
@FunctionalInterface
public interface Function<T,R> {
R apply(T t);
}
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
@FunctionalInterface
public interface Predicate<T>{
boolean test (T t);
}
@FunctionalInterface
public interface Supplier<T>{
T get();
}
public class FunctionTest {
public static void main(String[] args) {
// ‒ 在String类中有一个方法判断是否以指定的字符串开头:public boolean startsWith(String str)
Function<String,Boolean> function = "Hello"::startsWith;
System.out.println(function.apply("He"));
// ‒ 在进行系统数据输出的时候使用的是:System.out.println();
Consumer<String> consumer = System.out::println;
consumer.accept("hello");
// ‒ 在String类中提供有转小写方法,这个方法没有接收参数,但是有返回值
Supplier<String> supplier = "HElLO"::toLowerCase;
System.out.println("supplier:"+supplier.get());
// ‒ 在String类中有一个equalsIgnoreCase()方法
Predicate<String> predicate = "kuiyang"::equalsIgnoreCase;
System.out.println(predicate.test("KUIYANG"));
}
}
一般JDK自身提供了的函数式接口可以被我们使用,那么我们就没有必要重新定义了。