使用注解@FunctionalInterface标识,并且只包含一个抽象方法的接口是函数式接口。函数式接口主要分为:

  • Supplier供给型函数:Supplier的表现形式为不接受参数、只返回数据。
  • Consumer消费型函数:Consumer接收一个参数,没有返回值。
  • Runnable无参无返回型函数:Runnable的表现形式为即没有参数也没有返回值。
  • Function有参有返回型函数:Function函数的表现形式为接收一个参数,并返回一个值。

    1. Supplier

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

案例1:

  1. import org.junit.Test;
  2. import java.util.function.Supplier;
  3. public class Demo1 {
  4. public static int getMax(Supplier<Integer> sup) {
  5. return sup.get();
  6. }
  7. @Test
  8. public void c_求数组元素最大值() {
  9. int[] arr = {1, 5, 6, 4, 8, 7, 52, 2, 111};
  10. int max1 = getMax(() -> {
  11. int max = arr[0];
  12. for (int i = 1; i < arr.length; i++) {
  13. int temp = arr[i];
  14. if (temp > max) {
  15. max = temp;
  16. }
  17. }
  18. return max;
  19. });
  20. System.out.println("max1 = " + max1);
  21. }
  22. }

案例2:

  1. import org.junit.Test;
  2. import java.util.function.Supplier;
  3. public class Test01 {
  4. private static String getString(Supplier<String> function) {
  5. return function.get();
  6. }
  7. @Test
  8. public void c_() {
  9. String string = getString(() -> "hello" + "world");
  10. System.out.println("string = " + string);
  11. }
  12. }

2. Consumer

Consumer : 消费型接口 ,就是没有返回值.
void accept(T t);
java.util.function.Consumer 接口则正好与Supplier接口相反,它不是生产一个数据,而是消费一个数据,
其数据类型由泛型决定。
抽象方法:accept
Consumer 接口中包含抽象方法 void accept(T t) ,意为消费一个指定泛型的数据。

案例1:

  1. import java.util.function.Consumer;
  2. /**
  3. * 下面的字符串数组当中存有多条信息,请按照格式“ 姓名:XX。性别:XX。 ”
  4. * 的格式将信息打印出来。要求将打印姓名的动作作为第一个 Consumer 接口的Lambda实例,将打印性别的动作作为第二个 Consumer 接口的Lambda实例,将两个 Consumer 接口按照顺序“拼接”到一起。
  5. */
  6. public class Demo01 {
  7. public static void main(String[] args) {
  8. String[] array = {"迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男"};
  9. printInfo(s -> System.out.print("姓名:" + s.split(",")[0]),
  10. s -> System.out.println("。性别:" + s.split(",")[1] + "。"), array);
  11. }
  12. private static void printInfo(Consumer<String> one, Consumer<String> two, String[] array) {
  13. for (String info : array) {
  14. one.andThen(two).accept(info); // 姓名:迪丽热巴。性别:女。
  15. }
  16. }
  17. }

案例2:

  1. import java.util.function.Consumer;
  2. public class Test01 {
  3. private static void consumerString(Consumer<String> one, Consumer<String> two) {
  4. one.andThen(two).accept("Hello");
  5. }
  6. public static void main(String[] args) {
  7. consumerString(
  8. s -> System.out.println(s.toUpperCase()),
  9. s -> System.out.println(s.toLowerCase())
  10. );
  11. }
  12. }

3. Predicate

有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。这时可以使用 java.util.function.Predicate 接口。
Predicate : 断言型接口, 主要是用于做一些判断操作的.
boolean test(T t);

案例1:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.function.Predicate;
  4. public class Demo01 {
  5. /**
  6. * 数组当中有多条“姓名+性别”的信息如下,请通过 Predicate 接口的拼装将符合要求的字符串筛选到集合
  7. * ArrayList 中,需要同时满足两个条件:
  8. * 1. 必须为女生;
  9. * 2. 姓名为4个字。
  10. * @param args
  11. */
  12. public static void main(String[] args) {
  13. String[] array = {"迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男", "赵丽颖,女"};
  14. List<String> result = filter(array,
  15. s -> "女".equals(s.split(",")[1]),
  16. s -> s.split(",")[0].length() == 4
  17. );
  18. System.out.println(result);
  19. }
  20. private static List<String> filter(String[] array, Predicate<String> one, Predicate<String> two) {
  21. List<String> list = new ArrayList<>();
  22. for (String info : array) {
  23. if (one.and(two).test(info)) {
  24. list.add(info);
  25. }
  26. }
  27. return list;
  28. }
  29. }

案例2:


import org.junit.Test;

import java.util.function.Predicate;

public class Test01 {

    /**
     * “与”、“或”已经了解了,剩下的“非”(取反)也会简单。
     * 对结果boolean值进行“!”取反而已
     */
    @Test
    public void c_negate() {
        method3(s -> s.length()<5);
    }

    private static void method3(Predicate<String> predicate) {
        boolean veryLong = predicate.negate().test("HelloWorld");
        System.out.println(
                "字符串很长吗:" + veryLong);

    }

    private static void method2(Predicate<String> one, Predicate<String> two) {
        boolean isValid = one.or(two).test("Helloworld");
        System.out.println("字符串符合要求吗:" + isValid);

    }

    @Test
    public void c_or() {
        method2(s -> s.contains("H"),
                s -> s.contains("W")
        );

    }


    private static void method(Predicate<String> predicate) {
        boolean veryLong = predicate.test("HelloWorld");
        System.out.println("字符串很长吗:" + veryLong);

    }

    /**
     * 条件判断的标准是传入的Lambda表达式逻辑,只要字符串长度大于5则认为很长。
     */
    @Test
    public void c_2() {
        method(s -> s.length() > 5);
    }

    /**
     * and 方法
     * 如果要判断一个字符串既要包含大写“H”,又要包含大写“W”
     */
    @Test
    public void c_and() {


        method(s -> s.contains("H"),
                s -> s.contains("W")
        );

    }


    private static void method(Predicate<String> one, Predicate<String> two) {
        boolean isValid = one.and(two).test("Helloworld");
        System.out.println("字符串符合要求吗:" + isValid);

    }
}

4. Function

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

抽象方法:apply

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

Function : 函数型接口,传递进去一个T,你对这个T做个处理,返回给你一个R类型的值 当然你也可以声明成一样的,你传递一个String,给你返回一个String
R apply(T t);

案例1:


import java.util.function.Function;

/**
 * 请使用 Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
 * String str = “赵丽颖,20”;
 * 1. 将字符串截取数字年龄部分,得到字符串;
 * 2. 将上一步的字符串转换成为int类型的数字;
 * 3. 将上一步的int数字累加100,得到结果int数字。
 */
public class Demo01 {


    public static void main(String[] args) {

        String str = "赵丽颖,20";
        int age = getAgeNum(str, s -> s.split(",")[1],
                s -> Integer.parseInt(s), n -> n += 100

        );

        System.out.println(age);

    }



    private static int getAgeNum(String str, Function<String, String> one,

                                 Function<String, Integer> two,

                                 Function<Integer, Integer> three) {

        return one.andThen(two).andThen(three).apply(str);

    }
}

案例2:


import org.junit.Test;

import java.util.function.Function;

public class Test01 {


    private static void method(Function<String, Integer> function) {
        int num = function.apply("10");

        System.out.println(num + 20);

    }

    /**
     * apply
     */
    @Test
    public void c_apply() {


        method(s -> Integer.parseInt(s));


    }

    /**
     * Function 接口中有一个默认的 andThen 方法,用来进行组合操作
     * 该方法同样用于“先做什么,再做什么”的场景,和 Consumer 中的 andThen 差不多:
     * 第一个操作是将字符串解析成为int数字,第二个操作是乘以10。两个操作通过 andThen 按照前后顺序组合到了一起。
     * 请注意,Function的前置条件泛型和后置条件泛型可以相同。
     */
    @Test
    public void c_andThen() {

        method2(s -> Integer.parseInt(s) + 10, integer -> integer *= 10);
    }

    private static void method2(Function<String, Integer> one, Function<Integer, Integer> two) {
        int num = one.andThen(two).apply("10");

        System.out.println(num + 20);

    }

}