zoukankan      html  css  js  c++  java
  • Java8新特性

    Java内置的四大核心函数式接口

    Consumer:消费型接口

    对类型为T的对象应用操作,包含方法:void accept(T t)

    public class TestLambda02 {
        public static void main(String[] args) {
            testConsumer(9999, (x) -> {
               System.out.println("打游戏花费:" + x);
            });
        }
    
        public static void testConsumer(double money, Consumer<Double> consumer) {
            consumer.accept(money);
        }
    }
    

    Supplier:供给型接口

    返回包含类型为T的对象,包含方法:T get()

    public class TestLambda02 {
        public static void main(String[] args) {
            List<Integer> list = testSupplier(10, () -> (int)(Math.random() * 100));
            list.forEach(System.out::println);
        }
    
        public static List<Integer> testSupplier(int num, Supplier<Integer> supplier) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < num; i ++) {
                Integer n = supplier.get();
                list.add(n);
            }
            return list;
        }
    }
    

    Function<T, R>:函数型接口

    对类型为T的对象应用操作,并返回结果,结果类型为R。包含方法:R apply(T t)

    public class TestLambda02 {
        public static void main(String[] args) {
            String string = testFunction("哈哈哈哈哈哈哈", (str) -> str.substring(0, str.length() - 2));
            System.out.println("---->" + string);
        }
    
        public static String testFunction(String str, Function<String, String> function) {
            return function.apply(str);
        }
    }
    

    Predicate(T):断定型接口

    确定类型为T的对象是否满足某约束,并返回boolean值。包含方法:boolean test(T t)

    public class TestLambda02 {
        public static void main(String[] args) {
            System.out.println(testPredicate("哈哈哈哈皇后", (str) -> str.length() == 3));
        }
    
        public static boolean testPredicate(String string, Predicate<String> predicate) {
            return predicate.test(string);
        }
    }
    

    PS:除了这四个接口,java还内置了其他很多接口,这里不再赘述。可以在rt.jar文件下的java/util/function包下查看。

  • 相关阅读:
    Eclipse使用jre的原理与配置
    [笔记]Android开发环境配置及HelloWorld程序
    【足迹C++primer】38、关联容器操作(2)
    Linux ls 命令实现(简化版)
    POJ1149_PIGS(网络流/EK)
    调用存储过程取到数据通过NPOI存到Excel中
    python get post模拟请求
    常见软件应用
    Docker 镜像的导入和导出
    Linux 编译安装R语言
  • 原文地址:https://www.cnblogs.com/fx-blog/p/11743909.html
Copyright © 2011-2022 走看看