• Java8新特性(二)之函数式接口


    1. 什么是函数式接口

      1) 只包含一个抽象方法的接口

      2) 使用Lambda表达式去创建该对象。(若Lambda接口抛出一个受检异常,那么该异常需要在接口目标接口的抽象方法上进行声明)

      3) 在任何函数式接口上使用@FunctionalInterface注解,可以检查该接口中是否是一个函数式接口。

    2. 常用的JDK自定义的函数式接口(四大核心函数式接口)

        

      1) Consumer<T> 消费型接口

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

        

      2) Supplier<T> 供给型接口

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

        

      3) Function<T, R> 函数型接口

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

        

      4)Predicate<T> 断定型接口

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

        

    3. 自定义函数式接口

    案例一:

    /**
     * 自定义函数接口
     */
    @FunctionalInterface
    public interface MyFunctional {
        public int getValue();
    }

     使用测试:

     public static void main(String[] args) {
            List<Integer> intList = Arrays.asList(11,22,33,44,55);
            for (Integer i : intList) {
                MyFunctional myFunctional = () -> i;
                System.out.println(myFunctional.getValue());
            }
    
        }

    案例二(含泛型):

    /**
     * 待泛型的函数式接口
     * @param <T>
     * @param <R>
     */
    @FunctionalInterface
    public interface MyTwoArgsInterface<T, R> {
        public R retRstr(T t1, T t2);
    }

    测试案例二:

        @Test
        public void test() {
            MyTwoArgsInterface<Long, Long> mti =  (t1, t2) -> {
                return t1 + t2;
            };
            System.out.println(mti.retRstr(3l,4l));
        }
  • 相关阅读:
    文件下载的多种方法
    WebService返回DataTable问题
    PowerDesigner设置
    C#中简单的写日志的方法
    sql server 汉字的长度
    validateRequest="false"属性及xss攻击
    TotoiseSVN的基本使用方法
    有选择性的生成一个表的插入脚本,不是选择全部数据生成
    xml2-config not found.
    Ueditor编辑旧文章,从数据库中取出要修改的内容
  • 原文地址:https://www.cnblogs.com/sun-flower1314/p/11199831.html
Copyright © 2020-2023  润新知