一、四大内置核心函数式接口
Consumer<T>消费型接口:
//源码
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
//测试示例
@Test
void test(){
comsumerFunctionalTest("hello world!",e-> System.out.println(e));
}
void comsumerFunctionalTest(String msg,Consumer<String> consumer){
consumer.accept(msg);
}
Supplier<T>供给型接口:
//源码
@FunctionalInterface
public interface Supplier<T> {
T get();
}
//测试示例
@Test
void test(){
supplierFunctionalTest(()-> String.valueOf(new Random().nextInt()));
}
void supplierFunctionalTest(Supplier<String> supplier){
String result = supplier.get();
System.out.println(result);
}
Function<T, R>函数型接口:
//源码
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
//测试示例
@Test
void test(){
functionFunctionalTest(1024,(e)-> "num"+String.valueOf(e));
}
void functionFunctionalTest(Integer num,Function<Integer,String> function){
String result = function.apply(num);
System.out.println(result);
}
Predicate<T>断言型接口:
//源码
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
//测试示例
@Test
void test(){
predicateFunctionalTest("hello world!",(e)-> e.length()>5);
}
void predicateFunctionalTest(String name, Predicate<String> predicate){
boolean result = predicate.test(name);
System.out.println(result);
}
二、常用函数式接口
2.1 Runnable接口
//源码
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
//测试示例
@Test
void test(){
new Thread(()->{
System.out.println("hello world!");
},"thread-1").start();
}
2.2 Comparator<T>接口
//源码
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
//测试示例
@Test
void test(){
Student stu1 = new Student(23);
Student stu2 = new Student(24);
comparatorFunctionalTest(stu1,stu2,(e1,e2)-> Integer.compare(e1.getAge(),e2.getAge()));
}
void comparatorFunctionalTest(Student stu1, Student stu2, Comparator<Student> comparator){
int result = comparator.compare(stu1,stu2);
System.out.println(result);
}
2.3 GenericFutureListener接口
//源码
public interface GenericFutureListener<F extends Future<?>> extends EventListener {
void operationComplete(F var1) throws Exception;
}
//测试示例
private static final int MAX_RETRY = 5;
private static void connect(final String host,final int port,final int retry,final Bootstrap bootstrap){
bootstrap.connect(host,port).addListener(future -> {
if (future.isSuccess()){
System.out.println("客户端连接成功!");
}else if(retry == 0){
System.out.println("连接失败!");
}
else {
int order = (MAX_RETRY - retry) + 1;
int delay = 1 << order;
bootstrap.config().group().schedule(() -> connect(host, port, retry - 1, bootstrap), delay, TimeUnit.SECONDS);
}});
}
网友评论