jdk8函数式接口学习笔记

务必将jdk切换到1.8

函数式接口

1.1 概念

函数式接口在Java中是指:有且仅有一个抽象方法的接口

函数式接口,即适用于函数式编程场景的接口。而Java中的函数式编程体现就是Lambda,所以函数式接口就是可 以适用于Lambda使用的接口。只有确保接口中有且仅有一个抽象方法,Java中的Lambda才能顺利地进行推导。

备注:“语法糖”是指使用更加方便,但是原理不变的代码语法。例如在遍历集合时使用的for-each语法,其实

底层的实现原理仍然是迭代器,这便是“语法糖”。从应用层面来讲,Java中的Lambda可以被当做是匿名内部 类的“语法糖”,但是二者在原理上是不同的。

1.2 格式

只要确保接口中有且仅有一个抽象方法即可:

修饰符 interface 接口名称 { 

public abstract 返回值类型 方法名称(可选参数信息); //public abstract可以省略

// 其他非抽象方法内容 

}

1.3 @FunctionalInterface注解

与 @Override 注解的作用类似,Java 8中专门为函数式接口引入了一个新的注解: @FunctionalInterface 。该注 解可用于一个接口的定义上:

@FunctionalInterface 
public interface MyFunctionalInterface {
    void myMethod(); 
}

一旦使用该注解来定义接口,编译器将会强制检查该接口是否确实有且仅有一个抽象方法,否则将会报错。需要 的是,即使不使用该注解,只要满足函数式接口的定义,这仍然是一个函数式接口,使用起来都一样。

自定义函数式接口

public class Demo09FunctionalInterface { // 使用自定义的函数式接口作为方法参数 
    private static void doSomething(MyFunctionalInterface inter) {
        inter.myMethod(); // 调用自定义的函数式接口方法 
  	}
    public static void main(String[] args) {
        // 调用使用函数式接口的方法 
        doSomething(()> System.out.println("Lambda执行啦!")); 
    } 
}

lambda表达式:

用于函数式接口定义方法体

  public static void main(String[] args) {
      new Thread(() -> {
            System.out.println("+++++++++++");
        }).start();  
      new Thread(() -> System.out.println("============") ).start();

    }

//表示形式()->{},
//如果方法中只有一句代码,那么{}和代码后面的分号可以省略,
//如果方法中只传递一个参数那么可以将括号省略

常用函数式接口

Comparator接口

比较器中使用
下面对一个数组从大到小进行排序

public class ComparatorDemo {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(12,33,1,5,100);
        list.sort((o1,o2) ->  o1 - o2);
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
}

Supplier接口

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

public class SupplierDemo {
    private static String getString(Supplier<String> fun) {
        return fun.get();
    }

    public static void main(String[] args) {
        String str = "Hello";
        String str2 = "world";
        System.out.println(getString(() ->
             str + str2
        ));
    }
}

Consumer接口

java.util.function.Consumer 接口则正好与Supplier接口相反,它不是生产一个数据,而是消费一个数据, 其数据类型由泛型决定。

抽象方法:accept

Consumer 接口中包含抽象方法 void accept(T t) ,意为消费一个指定泛型的数据。基本使用如:


/**
字符串的反转
*/
public class ConsumerDemo {
    private static void consumerStr(Consumer<String > fun, String str) {
        fun.accept(str);
    }

    public static void main(String[] args) {
        String str = "hello world";
        consumerStr(s -> {
            StringBuffer reverse = new StringBuffer(s).reverse();
            System.out.println(reverse.toString());
        }, str);

    }
}

默认方法:andThen

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

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

例:

public class ConsumerAndThenDemo {
    private static void andThen(Consumer<String> fun1, Consumer<String> fun2) {
        fun1.andThen(fun2).accept("helloWorld");
    }

    public static void main(String[] args) {
        andThen(str1 -> {
            System.out.println(str1.toUpperCase());
        }, str2 -> {
            System.out.println(str2.toLowerCase());
        });
    }
}
//输出
//HELLOWORLD
//helloworld

案例

下面的字符串数组当中存有多条信息,请按照格式“ 姓名:XX。性别:XX。 ”的格式将信息打印出来

public class ConsumerDemo2 {
    public static void formatPrint(Consumer<String> fun1, Consumer<String> fun2, String[] array) {
        for (String s : array) {
            fun1.andThen(fun2).accept(s);
        }
    }

    public static void main(String[] args) {
        String[] array = {"迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男"};
        formatPrint(str -> {
            System.out.print("姓名:" +str.split(",")[0]);
        }, str -> {
            System.out.println("性别:" + str.split(",")[1]);

        }, array);
    }
}
Predicate接口

有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。这时可以使用

java.util.function.Predicate 接口。

抽象方法:test

Predicate 接口中包含一个抽象方法: boolean test(T t) 。用于条件判断的场景:

public class PredictDemo {

    private static boolean checkStr(Predicate<String> fun, String s) {
        return fun.test(s);
    }

    public static void main(String[] args) {
        String s = "hellow";
        boolean b = checkStr(str -> str.length() > 5, s);
        System.out.println(b);
    }
    ##### 默认方法:and

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

```java

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

实例:

public class PredictAndDemo {
    private static boolean validateStr(Predicate<String> fun1, Predicate<String> fun2, String str) {
        return fun1.and(fun2).test(str);
    }

    public static void main(String[] args) {
        String str = "Hello World";
        boolean b = validateStr(s -> s.contains("H"), s -> s.contains("W"), str);
        System.out.println(b);

    }
}

默认方法:or

与 and 的“与”类似,默认方法 or 实现逻辑关系中的“”。不过多解释

默认方法:negate

“与”、“或”已经了解了,剩下的“非”(取反)也会简单。默认方法 negate 的JDK源代码为:

default Predicate<T> negate() {
        return (t) -> !test(t);
    }
public class PredictDemo {

    private static boolean checkStr(Predicate<String> fun, String s) {
        return fun.negate().test(s);	//取反等价 !fun.test(s)
    }

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

案例

集合信息筛选

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

  1. 必须为女生;

  2. 姓名为4个字。


public class PredictDemo2 {
    private static void filter(Predicate<String> fun1, Predicate<String> fun2, String[] arr) {
        for (String s : arr) {
            boolean b =  fun1.and(fun2).test(s);
            if (b) {
                System.out.println(s);
            }
        }
    }

    public static void main(String[] args) {
        String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男", "赵丽颖,女" };
        filter(s -> s.split(",")[0].length() == 4,
                s -> s.contains("女"), array);
    }
}
Function接口

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

抽象方法:apply

Function 接口中最主要的抽象方法为: R apply(T t) ,根据类型T的参数获取类型R的结果。

使用的场景例如:将 String 类型转换为 Integer 类型。

public class functionDemo {
    private static int strToInteger(Function<String, Integer> fun, String str) {
        return fun.apply(str);
    }

    public static void main(String[] args) {
        String s = "12345";
        int i = strToInteger(s1 -> Integer.parseInt(s1), s);
        System.out.println(i);
    }
}

默认方法:andThen

Function 接口中有一个默认的 andThen 方法,用来进行组合操作。JDK源代码如:

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
}

String转Integer,Integer又转String

public class functionAndThenDemo {
    private static String andThen(Function<String, Integer> fun1, Function<Integer, String> fun2, String str) {
        return fun1.andThen(fun2).apply(str);
    }

    public static void main(String[] args) {
        String str = "123455";
        String i =  andThen(s -> Integer.parseInt(s) + 10,s2 -> s2 + "", str);
        System.out.println(i);
    }
}

案例

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

String str = “赵丽颖,20”

  1. 将字符串截取数字年龄部分,得到字符串;

  2. 将上一步的字符串转换成为int类型的数字;

  3. 将上一步的int数字累加100,得到结果int数字。

public class Demo {
    private static int getAge(Function<String, String> fun1, Function<String, Integer> fun2,
                              Function<Integer, Integer> fun3, String str) {
        return fun1.andThen(fun2).andThen(fun3).apply(str);
    }

    public static void main(String[] args) {
        String str = "赵丽颖,20";
        int age = getAge(s -> s.split(",")[1],
                s -> Integer.parseInt(s),
                s -> s + 100, str);
        System.out.println(age);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值