目录
概念:
有且仅有一个抽象方法的接口
如何检测一个接口是不是函数式接口
@Functionallnterface
放在接口定义的上方:如果接口是函数式接口,编译通过;如果不是,编译失败
注意事项:
我们自己定义函数式接口的时候,@Functionllnterface是可选的,就算不写这个注解,只要保证满足函数式接口定义的条件,也照样是函数式接口,但是,建议加上该注解
需求描述:
● 定义一个类(RunnableDemo),在类中提供两个方法
● 一个方法是:startThread(Runnable r)方法参数Runnable是一个函数式接口
● 一个方法是主方法,在主方法中调用startThread方法
代码演示:
- public class RunnableDemo {
- public static void main(String[] args) {
- //在主方法中调用startThread方法
- //匿名内部类的方式
- startThread(new Runnable() {
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName() + "线程启动了");
- }
- });
- //Lambda方式
- startThread(() -> System.out.println(Thread.currentThread().getName() + "线
- 程启动了"));
- }
- private static void startThread(Runnable r) {
- new Thread(r).start();
- }
- }
需求描述:
● 定义一个类(ComparatorDemo),在类中提供两个方法
● 一个方法是:Compartor getComparator()方法返回值Comparator是已给函数式接口
● 一个方法是主方法,在主方法中调用getComparator方法
代码演示:
- public class ComparatorDemo {
- public static void main(String[] args) {
- //定义集合,存储字符串元素
- ArrayList
array = new ArrayList(); - array.add("cccc");
- array.add("aa");
- array.add("b");
- array.add("ddd");
- System.out.println("排序前:" + array);
- Collections.sort(array, getComparator());
- System.out.println("排序后:" + array);
- }
- private static Comparator
getComparator() { - //匿名内部类的方式实现
- return new Comparator
() { - @Override
- public int compare(String s1, String s2) {
- return s1.length()-s2.length();
- }
- };
- //Lambda方式实现
- return (s1, s2) -> s1.length() - s2.length();
- }
- }
Supplier接口:
Supplier接口也被称为生产型接口,如果我们指定了接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据供我们使用、
常用方法:只有一个无参的方法
方法名 | 说明 |
T get() | 按照某种实现逻辑(由Lambda表达式实现)返回一个数据 |
代码演示:
- public class SupplierDemo {
- public static void main(String[] args) {
- String s = getString(() -> "小林");
- System.out.println(s);
-
- Integer i = getInteger(() -> 20);
- System.out.println(i);
- }
-
- //定义一个方法,返回一个整数数据
- private static Integer getInteger(Supplier
sup) { - return sup.get();
- }
-
- //定义一个方法,返回一个字符串数据
- private static String getString(Supplier
sup) { - return sup.get();
- }
- }
案例需求:
定义一个类(SupplierTest),在类中提供两个方法
一个方法是:int getMax(Supplier sup)用于返回一int数组中的最大值
一个方法是主方法,在主方法中调用getMax方法
示例代码:
- public class SupplierTest {
- public static void main(String[] args) {
- //定义一个int数组
- int[] arr = {19, 50, 28, 37, 46};
-
- int maxValue = getMax(()-> {
- int max = arr[0];
-
- for(int i=1; i
- if(arr[i] > max) {
- max = arr[i];
- }
- }
- return max;
- });
- System.out.println(maxValue);
- }
-
- //返回一个int数组中的最大值
- private static int getMax(Supplier
sup) { - return sup.get();
- }
- }