【Java】函数式编程

1 函数式接口

1.1 概念

函数式接口是有且仅有一个抽象方法的接口,可以包括静态和默认方法。

@FunctionalInterface:加上注解,检测是否的函数式接口

@FunctionalInterface
public interface MyFunctionInterface {

    public abstract void method();

    static void method2() {

    }

    default void method3() {
        
    }
}

1.2 函数式接口的使用

一般可以作为方法的参数返回值类型

    public static void show(MyFunctionInterface myInter){
        myInter.method();
    }
    public static void main(String[] args) {
        show(new MyFunctionInterface() {
            @Override
            public void method() {
                System.out.println("使用匿名内部类重写接口中的抽象方法");
            }
        });
        
        show(()->{
            System.out.println("使用lambda表达式重写接口的抽象方法");
        });
        
        show(()-> System.out.println("使用简化lambda表达式重写接口的抽象方法"));
    }

2 函数式编程

2.1 性能浪费案例

public static void showLog(int level, String message){
        if(level==1){
            System.out.println(message);
        }
    }

    public static void main(String[] args) {
        String msg1 = "Hello";
        String msg2 = "Hello";
        String msg3 = "Hello";
        showLog(1,msg1+msg2+msg3);
    }

调用showLog方法,第二个参数式拼接后的字符串,如果等级不是1,message不需要输出,存在浪费。

2.2 Lambda优化案例

@FunctionalInterface
public interface MessageBuider {
    String buiderMessage();
}
public static void showLog(int level, MessageBuider mb){
        if(level==1){
            System.out.println(mb.buiderMessage());;
        }
    }

    public static void main(String[] args) {
        String m1 = "Hello";
        String m2 = "Zhangsan";
        showLog(1, ()->{
                return m1+m2;
        });
    }

这里只有满足条件才会调用接口的方法进行字符串拼接。如果不满足就不会进行字符串拼接,没有了性能的浪费。

2.3 使用Lambda作为参数和返回值

作为参数

//Runnable是一个函数式接口
    public static void startThread(Runnable run){
        new Thread(run).start();
    }
    public static void main(String[] args) {
        startThread(()->
            System.out.println("开启线程"+Thread.currentThread().getName())
        );
    }

作为返回值

//Comparator是一个函数式接口
    public static Comparator<String> getComparator(){
        return (o1, o2) -> o2.length()-o1.length();
    }
    public static void main(String[] args) {
        String[] arr = {"aaa","bbbbb","cccccc"};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//[aaa, bbbbb, cccccc]
        Arrays.sort(arr,getComparator());
        System.out.println(Arrays.toString(arr));//[cccccc, bbbbb, aaa]
    }

3 常用的函数式接口

3.1 Supplier接口

仅包含一个无参方法:T get()
用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。

//    Supplier<String>作为参数
    public static String getString(Supplier<String> sup){
        return sup.get();
    }
    public static void main(String[] args) {
        String str = getString(()->"哈哈哈");
        System.out.println(str);
    }

练习:应用Supplier求数组最大值

	public static int getMax(Supplier<Integer> sup){
        return sup.get();
    }

    public static void main(String[] args) {
        int[] arr = {5,6,2,4,1,7,3};
        int ans = getMax(() -> {
            int max = arr[0];
            for (int i : arr) {
                if (i > max) {
                    max = i;
                }
            }
            return max;
        });
        System.out.println(Arrays.toString(arr));//[5, 6, 2, 4, 1, 7, 3]
        System.out.println(ans);//7
    }

3.2 Consumer接口

consumer接口是一个消费型接口,泛型执行什么类型,可以使用accept方法消费什么类型的数据,至于怎么消费,需要自定义。

    public static void method(String name, Consumer<String> con){
        con.accept(name);
    }

    public static void main(String[] args) {
        //消费方式:输出
        method("张三", (name)->{
            System.out.println(name);
        });
        //可以替换为method("张三", System.out::println);

        //消费方式:反转输出
        method("张三",(name)->{
            System.out.println(new StringBuilder(name).reverse().toString());
        });
    }

默认方法andThen:如果一个方法的参数和返回值全都是Consumer 类型,那么就可以实现效果:消费数据的时候,首先做一个操作,然后再做一个操作,实现组合。而这个方法就是Consumer 接口中的default方法andThen

default Consumer<T> andThen(Consumer<? super T> after) {
	Objects.requireNonNull(after);
	return (T t)> { accept(t); after.accept(t); };
}

备注: java.util.Objects 的requireNonNull 静态方法将会在参数为null时主动抛出
NullPointerException 异常。这省去了重复编写if语句和抛出空指针异常的麻烦。

    public static void method(String name, Consumer<String> con1, Consumer<String> con2){
        con1.andThen(con2).accept(name);

        //相当于👇
//        con1.accept(name);
//        con2.accept(name);
    }

    public static void main(String[] args) {
        //消费方式:将字符串转换为大写输出
        method("HEllo",
                (t)->{
                    System.out.println(t.toLowerCase());
                },
                (t)->{
                    System.out.println(t.toUpperCase());
                }
                );
    }

练习andThen:格式化打印信息
下面的字符串数组当中存有多条信息,请按照格式“ 姓名:XX。性别:XX。”的格式将信息打印出来。要求将打印姓名的动作作为第一个Consumer 接口的Lambda实例,将打印性别的动作作为第二个Consumer 接口的Lambda实例,将两个Consumer 接口按照顺序“拼接”到一起。

    public static void method(String[] arr, Consumer<String> con1, Consumer<String> con2){
        for(String str: arr){
            con1.andThen(con2).accept(str);
        }
    }

    public static void main(String[] args) {
        String[] array = { "张三,男", "李四,男", "王五,女" };
        method(array,(str)->{
            String[] split = str.split(",");
            System.out.print("姓名:"+split[0] + "。");

        },(str)->{
            String[] split = str.split(",");
            System.out.println("性别:"+split[1]+"。");
        });
    }

3.3 Predicate接口

作用:对数据类型的数据进行判断,结果返回boolean值

抽象方法test:用来对指定数据类型的数据进行判断的方法

    public static boolean checkString(String s, Predicate<String> pre){
        return pre.test(s);
    }

    public static void main(String[] args) {
        String s = "abcd";
        boolean check = checkString(s, (str) -> str.length() > 5);
        System.out.println(check);
    }

默认方法and
既然是条件判断,就会存在与、或、非三种常见的逻辑关系。其中将两个Predicate 条件使用“与”逻辑连接起来实现“并且”的效果时,可以使用default方法and 。其JDK源码为:

default Predicate<T> and(Predicate<? super T> other) {
	Objects.requireNonNull(other);
	return (t)> test(t) && other.test(t);
}

定义两个判断条件:字符串长度大于5,字符串包含a,条件要同时满足

    public static boolean checkString(String s, Predicate<String> pre1, Predicate<String> pre2){
        return pre1.and(pre2).test(s);
        //相当于👇
        //return pre1.test(s) && pre2.test(s);
    }

    public static void main(String[] args) {
        String s = "abcdef";
        boolean check = checkString(s, (str) -> str.length() > 5,(str) -> str.contains("a"));
        System.out.println(check);
    }

默认方法or
与and 的“与”类似,默认方法or 实现逻辑关系中的“或”。JDK源码为:

default Predicate<T> or(Predicate<? super T> other) {
	Objects.requireNonNull(other);
	return (t)> test(t) || other.test(t);
}

定义两个判断条件:字符串长度大于5,字符串包含a,条件满足一个即可

    public static boolean checkString(String s, Predicate<String> pre1, Predicate<String> pre2){
        return pre1.or(pre2).test(s);
        //相当于👇
//        return pre1.test(s) || pre2.test(s);
    }

    public static void main(String[] args) {
        String s = "a";
        boolean check = checkString(s, (str) -> str.length() > 5,(str) -> str.contains("a"));
        System.out.println(check);
    }

默认方法negate:“非”(取反)默认方法negate 的JDK源代码为:

default Predicate<T> negate() {
	return (t)> !test(t);
}
	public static boolean checkString(String s, Predicate<String> pre){
        return pre.negate().test(s);
        //相当于👇
        //return !pre.test(s);
    }

    public static void main(String[] args) {
        String s = "a";
        boolean check = checkString(s, (str) -> str.length() > 5);
        System.out.println(check);
    }

练习:信息集合筛选
数组当中有多条“姓名+性别”的信息如下,请通过Predicate 接口的拼装将符合要求的字符串筛选到集合ArrayList 中,需要同时满足两个条件:

  1. 必须为女生;
  2. 姓名大于等于3个字。
	public static ArrayList<String> filterPerson(String[] arr, Predicate<String> pre1, Predicate<String> pre2) {
        ArrayList<String> list = new ArrayList<>();
        for (String str : arr) {
            if (pre1.and(pre2).test(str)) {
                list.add(str);
            }
        }
        return list;
    }

    public static void main(String[] args) {
        String[]  arr = {"张三,男","张三三,女","李四,男","李四四,女","王五,女","王五五,男"};
        ArrayList<String> list = filterPerson(arr, (str) -> {
            String[] split = str.split(",");
            return "女".equals(split[1]);
        }, (str) -> {
            String[] split = str.split(",");
            return split[0].length() >= 3;
        });
        for (String s:list) {
            System.out.println(s);
        }
    }

3.4 Function接口

java.util.function.Function<T,R> 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。

使用场景:根据类型T的参数获取类型R的结果

抽象方法:apply

	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, (str)->{return Integer.parseInt(s);});
    }

默认方法:andThen
把String类型的123转换为Integer类型,加上10后,再转为String类型输出

	public static void change(String s, Function<String, Integer> fun1, Function<Integer, String> fun2){
        String strout = fun1.andThen(fun2).apply(s);
        //fun1先调用apply把字符串转为Integer
        //fun2再调用apply把Integer转为字符串
        System.out.println(strout);
    }

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

练习:自定义函数模型的拼接
请使用Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:

  1. 将字符串截取数字年龄部分,得到字符串;
  2. 将上一步的字符串转换成为int类型的数字;
  3. 将上一步的int数字累加100,得到结果int数字。
	//1. 将字符串截取数字年龄部分,得到字符串;
    //2. 将上一步的字符串转换成为int类型的数字;
    //3. 将上一步的int数字累加100,得到结果int数字。
    public static void change(String s, Function<String, String> fun1,
                              Function<String, Integer> fun2, 
                              Function<Integer, Integer> fun3){
        Integer num = fun1.andThen(fun2).andThen(fun3).apply(s);
        System.out.println(num);
    }

    public static void main(String[] args) {
        String s1 = "张三:20";
        change(s1, (str)->{
            String[] split = s1.split(":");
            return split[1];
        },(s2)->{
            return Integer.parseInt(s2);
            },(num)->{
            return num+100;});
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值