zoukankan      html  css  js  c++  java
  • java8中规范的四大函数式接口

         java8中规范的四大函数式接口:

         1、Consumer<T>   :消费型接口    void accept(T t);

         2、Supplier<T>      :供给型接口    T get();

         3、Function<T,R>   :函数型接口    R apply(T t);

         4、Predicate<T>    :断言型接口    boolean test(T t);

    事例一:

     1 /**
     2  * 消费形接口,有参数,无返回值
     3  */
     4 public class ConsumerTest {
     5 
     6   public static void main(String[] args) {
     7 
     8     summer(10000, m -> System.out.println("世界那么大,我想去看看,可是钱包仅有:"+m+"元"));
     9 
    10   }
    11 
    12   public static void summer(double money, Consumer<Double> con) {
    13     con.accept(money);
    14   }
    15 }

    结果:

    事例二:

     1 /**
     2  * 供给形接口,无参数有返回值
     3  */
     4 public class SupplierTest {
     5 
     6   public static void main(String[] args) {
     7 
     8     List<Double> list = getRandomValue(5, () -> Math.random() * 100);
     9     for (Double d : list) {
    10       System.out.println(d);
    11     }
    12   }
    13 
    14   public static List<Double> getRandomValue(int num, java.util.function.Supplier<Double> sup) {
    15     List<Double> list = new ArrayList<>();
    16     for (int i = 0; i < num; i++) {
    17       list.add(sup.get());
    18     }
    19     return list;
    20   }
    21 }

    结果:

     结果:

    事例三:

    /**
     * 函数形接口,有参数,有
     */
    public class ConsumerTest {
    
      public static void main(String[] args) {
    
        String str = strHandler("一花一世界,一叶一菩提!", s -> s.substring(2,5));
        System.out.println(str);
      }
      public static String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
      }
    }

    结果:

    事例四:

     1 /**
     2  * 断言形接口,有参数,返回boolean
     3  */
     4 public class PredicateTest {
     5 
     6   public static void main(String[] args) {
     7 
     8     List<String> list = Arrays.asList("北京","南京","东京","长安","洛阳");
     9     list = filterStr(list, s->s.contains("京"));
    10     list.forEach(System.out::println);
    11   }
    12 
    13   public static List<String> filterStr(List<String> list, Predicate<String> predicate) {
    14     List<String> stringList = new ArrayList<>();
    15     for (String str : list) {
    16       if (predicate.test(str))
    17         stringList.add(str);
    18     }
    19     return stringList;
    20   }
    21 }

    结果:

    想要飞得更高,就该忘记地平线!
  • 相关阅读:
    Jenkins构建时间Poll Scm的设置(常用设置)
    jenkins对测试脚本的构建步骤
    jemeter排至数据库时报:Access denied for user 'root'@'localhost' (using password:YES) 解决方案
    接口测试总结
    linux gitlab-ctl reconfigure报错问题修复 502
    Linux Redis 开机启动
    CentOS7安装iptables防火墙
    linux mongodb开机启动(服务的方式)
    Linux服务器使用XShell上传下载文件
    推荐.Net、C# 逆向反编译四大工具利器
  • 原文地址:https://www.cnblogs.com/shenwen/p/11015220.html
Copyright © 2011-2022 走看看