Java(函数式接口)

一.函数式接口

1)概念
    有且仅有一个抽象方法的接口

2)@FunctionalInterface注解
    作用:可以检测接口中是否是一个函数式接口
      是:编译成功
      否:编译失败

3)lambda表达式延迟加载问题,lambda的使用前提:必须存在函数时接口

二.常用的函数式接口

JDK提供了大量常用的函数式接口以丰富Lambda的典型使用场景,在java.util.function中

2.1 Supplier接口

1)概念
    java.util.function.Supplier<>
    Supplier<T>接口:称为生产型接口,指定接口的泛型是什么类型,那么接口中get方法就会生产什么类型的数据
    Supplier<T>接口是一个函数式接口

2)代码实现
    public  static String getString(Supplier<String> sup){
            return sup.get();
        }

        public static void main(String[] args) {
            String s = getString(() -> {
                return "张三";
            });
            System.out.println(s);//张三
            //优化Lambda表达式
            String s2 = getString(() ->  "张三");
            System.out.println(s2);//张三
        }
3)例题:求数组元素最大值

    public class Test {
        //定义一个方法,用于获取int类型数组中元素的最大值,
        //接口泛型使用Integer类型
        public static int getMax(Supplier<Integer> sup) {
            return sup.get();
        }

        public static void main(String[] args) {
            int arr[] = {1, 3, 8, 5, 7};
            //调用getMax方法,Supplier是一个函数式接口,所以可以传递lambda表达式
            int maxValue = getMax(() -> {
                //获取数组最大值,并返回
                //定义一个变量,记录数组中的最大值
                int max = arr[0];
                //遍历数组
                for (int i : arr) {
                    //使用其他元素和最大值比较
                    if (i > max) {
                        max = i;
                    }
                }
                return max;
            });
            System.out.println("数组中最大值为:"+maxValue);
        }
    }

2.2 Consumer接口

1)概念
    Consumer接口是一个消费型接口,
        泛型指定什么类型,就可以使用accept方法消费什么类型的数据
        具体怎么消费,需要自定义(输出,计算)
2)实现代码

    public class Test {
    /*
    定义一个方法
    方法的参数传递一个字符串的姓名
    方法的参数传递Consumer接口,泛型使用String
    可以使用Consumer接口消费字符串的姓名
     */
        public static void method(String name, Consumer<String> con) {
           con.accept(name);
        }

        public static void main(String[] args) {
    //调用method方法,传递姓名,Consumer是一个函数式接口,可以使用lanmda表达式
            method("耗子未至",(String name)->{
                System.out.println(name);
                //消费方式:字符串反转
                String reName=new StringBuffer(name).reverse().toString();
                System.out.println(reName);
            });
        }
    }

3)默认方法:andThen
    作用:需要两个Consumer接口,可以把两个Consumer接口组合到一起,对数据进行消费
    例如:con1.andThen(con2).accept(string);

2.3 Predicate接口

1)概念
    java.util.function.Predicate<T>接口
    作用:对某种数据类型的数据进行判断,结果返回boolean值
      boolean test(T t):用来对指定数据类型数据进行判断的方法
        结果:符合条件为true

2)代码实现
    public class Test {

    public static boolean checkString(String s, Predicate<String> pre){
        return pre.test(s);
    }
        public static void main(String[] args) {
        //定义一个字符串
            String s="abcde";
            //使用checkString方法对字符串校验,参数传递字符串和Lambda表达式
            boolean b= checkString(s,(String str)->{
                //对参数传递的字符串进行判断,判断字符串的长度是否大于5
                return str.length()>5;
            });
            System.out.println(b);
        }
    }

3)默认方法
    and:相当于&&
    or:相当于||
    negate:相当于!

4)信息筛选案例
   public class Test {
    /*
    信息筛选:
    一个数组 String arr[]={"地热,女","古力娜扎,女","马儿扎哈,男"}
    要求:
        同时满足两个条件:1.为女生 2.姓名:为4个字
    分析:
    1.使用两个Predivate接口and方法 同时满足两个条件
     */
    public static ArrayList<String> filter(String[] arr, Predicate<String> pre1,Predicate<String> pre2){
        //list集合:存储过滤之后的信息
        ArrayList<String> list = new ArrayList<>();
        //遍历数组
        for (String s : arr) {
            //使用Predicate接口中test方法对获取的字符串判断
            boolean b = pre1.and(pre2).test(s);
            //判断
            if (b){
                //条件成立,存储到list集合中
                list.add(s);
            }
        }
        return list;
    }
        public static void main(String[] args) {
            String arr[]={"地,女","古力娜扎,女","马儿扎哈,男"};
          ArrayList<String> list = filter(arr,(String s)->{
                //获取字符串性别:判断性别
               return s.split(",")[1].equals("女");
            },(String s)->{
                //获取字符串中姓名:判断个数
                return s.split(",")[0].length()==4;
            });
          //遍历集合
            for (String s : list) {
                System.out.println(s);
            }
        }
    }

2.4 Function接口

1)概念
java.util.function.Function<T,R>接口
作用:类型转换
使用apply方法,例如将String类型转换为Interger类型

2)代码实现

public class Test {

    //将String类型转换为Interger
    public static void change(String s, Function<String,Integer> fun){
        Integer in = fun.apply(s);
        System.out.println(in);

    }
    public static void main(String[] args) {
        String s="1234";
        change(s,(String str)->{
           return Integer.parseInt(str);
        });
    }
}

3)默认方法
andThen:用来组合操作

posted @ 2021-04-06 22:44  一名初学者  阅读(134)  评论(0)    收藏  举报