Java 之 常用函数式接口

  JDK提供了大量常用的函数式接口以丰富Lambda的典型使用场景,它们主要在 java.util.function 包中被提供。
下面是最简单的几个接口及使用示例。

一、Supplier 接口

  java.util.function.Supplier<T> 接口仅包含一个无参的方法: T get() 用来获取一个泛型参数指定类型的对象数据。

  由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要对外提供一个符合泛型类型的对象数据。(生产接口) 

  Demo:

 1  import java.util.function.Supplier;
 2 
 3     public class Demo08Supplier {
 4         private static String getString(Supplier<String> function) {
 5             return function.get();
 6         }
 7 
 8         public static void main(String[] args) {
 9             String msgA = "Hello";
10             String msgB = "World";
11             System.out.println(getString(() ‐ > msgA + msgB));
12         }
13     }

  案例:求数组元素最大值

  题目:使用 Supplier 接口作为方法参数类型,通过Lambda表达式求出int数组中的最大值。

  提示:接口的泛型请使用 java.lang.Integer

    代码实现:

 1 public class DemoTest {
 2         //定一个方法,方法的参数传递Supplier,泛型使用Integer
 3         public static int getMax(Supplier<Integer> sup){
 4             return sup.get();
 5         } 
 6         public static void main(String[] args) {
 7             int arr[] = {2,3,4,52,333,23};
 8             //调用getMax方法,参数传递Lambda
 9             int maxNum = getMax(()‐>{
10                 //计算数组的最大值
11             int max = arr[0];
12             for(int i : arr){
13                 if(i>max){
14                     max = i;
15                 }
16             } 
17             return max;
18             });
19             System.out.println(maxNum);
20         }
21     }

二、Consumer 接口

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

  (1)抽象方法:accept

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

 1 import java.util.function.Consumer;
 2 
 3     public class DemoConsumer {
 4         private static void consumeString(Consumer<String> function) {
 5             function.accept("Hello");
 6         }
 7 
 8         public static void main(String[] args) {
 9             consumeString(s ‐ > System.out.println(s));
10         }
11     }

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

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

  要想实现组合,需要两个或多个Lambda表达式即可,而 andThen 的语义正是一步接一步操作。例如两个步骤组合的情况:

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

  运行结果将会首先打印完全大写的HELLO,然后打印完全小写的hello。当然,通过链式写法可以实现更多步骤的组合。 

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

   代码实现:

 1 import java.util.function.Consumer;
 2     public class DemoConsumer {
 3         public static void main(String[] args) {
 4             String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男" };
 5             printInfo(s ‐> System.out.print("姓名:" + s.split(",")[0]),
 6                     s ‐> System.out.println("。性别:" + s.split(",")[1] + "。"),
 7                     array);
 8         } 
 9         private static void printInfo(Consumer<String> one, Consumer<String> two, String[] array) {
10             for (String info : array) {
11                 one.andThen(two).accept(info); // 姓名:迪丽热巴。性别:女。
12             }
13         }
14     }

 

三、Predicate 接口

  有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。这时可以使用java.util.function.Predicate<T> 接口。

  (1)抽象方法:test

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

 1 import java.util.function.Predicate;
 2 
 3     public class DemoPredicateTest {
 4         private static void method(Predicate<String> predicate) {
 5             boolean veryLong = predicate.test("HelloWorld");
 6             System.out.println("字符串很长吗:" + veryLong);
 7         }
 8 
 9         public static void main(String[] args) {
10             method(s ‐ > s.length() > 5);
11         }
12     }

    条件判断的标准是传入的Lambda表达式逻辑,只要字符串长度大于5则认为很长。

  (2)默认方法:and

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

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

    如果要判断一个字符串既要包含大写“H”,又要包含大写“W”,那么:

 1 import java.util.function.Predicate;
 2 
 3     public class Demo16PredicateAnd {
 4         private static void method(Predicate<String> one, Predicate<String> two) {
 5             boolean isValid = one.and(two).test("Helloworld");
 6             System.out.println("字符串符合要求吗:" + isValid);
 7         }
 8 
 9         public static void main(String[] args) {
10             method(s ‐ > s.contains("H"), s ‐>s.contains("W"));
11         }
12     }

  (3)默认方法:or

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

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

     如果希望实现逻辑字符串包含大写H或者包含大写W”,那么代码只需要将“and”修改为“or”名称即可,其他都不变:

 1 import java.util.function.Predicate;
 2 
 3     public class Demo16PredicateAnd {
 4         private static void method(Predicate<String> one, Predicate<String> two) {
 5             boolean isValid = one.or(two).test("Helloworld");
 6             System.out.println("字符串符合要求吗:" + isValid);
 7         }
 8 
 9         public static void main(String[] args) {
10             method(s ‐ > s.contains("H"), s ‐>s.contains("W"));
11         }
12     }

 

  (4)默认方法:negate

     取“非”是 negate方法,JDK源代码为:

1 default Predicate<T> negate() {
2     return (t) ‐> !test(t);
3 }

  从实现中很容易看出,它是执行了test方法之后,对结果boolean值进行“!”取反而已。一定要在 test 方法调用之前调用 negate 方法,正如 and or 方法一样:

 1 import java.util.function.Predicate;
 2 
 3     public class Demo17PredicateNegate {
 4         private static void method(Predicate<String> predicate) {
 5             boolean veryLong = predicate.negate().test("HelloWorld");
 6             System.out.println("字符串很长吗:" + veryLong);
 7         }
 8 
 9         public static void main(String[] args) {
10             method(s ‐ > s.length() < 5);
11         }
12     }

 

  (5)案例:集合信息筛选

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

        ① 必须为女生;② 姓名为4个字

    代码实现:

 1     import java.util.ArrayList;
 2     import java.util.List;
 3     import java.util.function.Predicate;
 4 
 5     public class DemoPredicate {
 6         public static void main(String[] args) {
 7             String[] array = {"迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男", "赵丽颖,女"};
 8             List<String> list = filter(array,
 9                     s ‐> "女".equals(s.split(",")[1]),
10                  s ‐>s.split(",")[0].length() == 4);
11             System.out.println(list);
12         }
13 
14         private static List<String> filter(String[] array, Predicate<String> one,
15                                            Predicate<String> two) {
16             List<String> list = new ArrayList<>();
17             for (String info : array) {
18                 if (one.and(two).test(info)) {
19                     list.add(info);
20                 }
21             }
22             return list;
23         }
24     }

四、Function 接口

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

  (1)抽象方法:apply

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

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

 1 import java.util.function.Function;
 2 
 3     public class Demo11FunctionApply {
 4         private static void method(Function<String, Integer> function) {
 5             int num = function.apply("10");
 6             System.out.println(num + 20);
 7         }
 8 
 9         public static void main(String[] args) {
10             method(s ‐ > Integer.parseInt(s));
11         }
12     }

 

  (2)默认方法:andThen

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

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

     该方法同样用于先做什么,再做什么的场景,和 Consumer 中的 andThen 差不多:

 1 import java.util.function.Function;
 2 
 3     public class Demo12FunctionAndThen {
 4         private static void method(Function<String, Integer> one, Function<Integer, Integer> two) {
 5             int num = one.andThen(two).apply("10");
 6             System.out.println(num + 20);
 7         }
 8 
 9         public static void main(String[] args) {
10             method(str‐ > Integer.parseInt(str) + 10, i ‐>i *= 10);
11         }
12     }

  第一个操作是将字符串解析成为int数字,第二个操作是乘以10。两个操作通过 andThen 按照前后顺序组合到了一起。

   注意Function的前置条件泛型和后置条件泛型可以相同。

猜你喜欢

转载自www.cnblogs.com/niujifei/p/11614257.html
今日推荐