函数是接口
1.首先函数式接口是一个接口
2.接口内只有一个方法,该方法还是缺省属性的public static
常用的函数式接口
Comparator
Runnable
Lambda表达式对比匿名内部类使用
- 简化了代码结构
.2. 节约了内存资源
3.让程序员更加关注,我要做什么,而不是为了做 什么需要完成什么
** @FunctionalInterface **
函数式接口的格式检查,类试于重写检查的@Override,要求被规定的接口中只能有一个缺省属性为public abstract修饰的方法
/**
* 使用@FunctionalInterface检查函数式接口格式问题
*
*
* 要求当前接口中有且只有一个缺省属性为public abstract的方法
*
* @author Anonymous 2020/3/11 9:55
*/
@FunctionalInterface
public interface FunctionalType {
void test();
}
自定义函数式接口的使用
函数是接口的延迟使用
package com.qfedu.lqqtest;
enum Level{
High,Mid,Low
}
/**
* date: 2020/3/11 12:20
*
* @author lqq
* @since JDK 1.8
*/
public class Demo1 {
public static void main(String[] args) {
useFunctionInterface(Level.High, new FunctionInterface() {
@Override
public String getMsg() {
System.out.println("Lambda表达式执 行!!!");
return "刘嘻嘻";
}
});
useFunctionInterface(Level.Mid, new FunctionInterface() {
@Override
public String getMsg() {
System.out.println("Lambda表达式执 行!!!");
return "刘嘻嘻";
}
});
// useFunctionInterface(Level.High,()-> {return "lxx";});
// getMsg(Level.Mid,"刘嘻嘻");
}
public static void getMsg(Level level,String msg){
if (Level.High == level){
System.out.println(msg);
}
}
public static void useFunctionInterface(Level level,FunctionInterface fi){
//判断结果不成立,不会执行接口函数式接口
if (Level.High == level){
System.out.println(fi.getMsg());
}
}
}
Lambda作为方法参数和返回值
参数演示: Runnable接口
package com.qfedu.lqqtest;
/**
* date: 2020/3/11 12:48
*
* @author lqq
* @since JDK 1.8
*/
public class TestRunnable {
public static void main(String[] args) {
new Thread(() -> System.out.println("线程启动")).start();
new Thread(new Runnable() {
// 匿名内部类来完成对应当前Runnable接口实现 类对象使用,作为Thread构造方法参数
@Override
public void run() {
System.out.println("线程创建");
}
}).start();
Thread thread = new Thread(() -> {
System.out.println("线程创建");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("创建完成");
});
thread.start();
}
}
Java中提供的比较接口Comparator
利用一些返回值作为方法中操作的调节
public interface Comparator {
int compare(T o1, T o2); }
package com.qfedu.lqqtest;
import java.util.Arrays;
import java.util.Comparator;
/**
* date: 2020/3/11 12:54
*
* @author lqq
* @since JDK 1.8
*/
public class TestComparator {
public static void main(String[] args) {
String[] arr = {"刘嘻11111嘻","鲁千旗","嘻嘻嘻"};
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
});
Arrays.sort(arr,(o1,o2)->{
return o2.length()-o1.length();
});
System.out.println( Arrays.toString(arr));
}
}