Java——函数式接口和lambda表达式

来源:互联网 发布:大智慧全推数据 编辑:程序博客网 时间:2024/06/08 19:36

简介

    /**     * 函数式接口:只定义了唯一的抽象方法的接口,会使用@FunctionalInterface该注解     * Comparator     * Callable     * Runnable     * Function<T, R> -T作为输入,返回的R作为输出     * Predicate<T> -T作为输入,返回的boolean值作为输出     * Consumer<T> - T作为输入,执行某种动作但没有返回值     * Supplier<T> - 没有任何输入,返回T     * UnaryOperator -- 一元操作符, 继承Function,传入参数的类型和返回类型相同     * BinaryOperator<T> -两个T作为输入,返回一个T作为输出,对于“reduce”操作很有用     *     * Lambda表达式:Lambda:()->{}     *     */    @Test    public void trans() {        //有参数有返回值        Comparator<Integer> com = (x, y) -> {            System.out.println("hello3");            return Integer.compare(x, y);//0相等;1 x>y;-1 x<y        };        int rs = com.compare(6, 4);        System.out.println(rs);        //右侧如果只有一条执行语句,可以省略大括号和return        System.out.println("hello!");        Comparator<Integer> coms = (x, y) -> Integer.compare(x, y);        int rss = com.compare(2, 2);        System.out.println(rss);        // 返回boolean        Predicate<String> check=(str)->str.equals("lambda");         check.test("d");        System.out.println(rs);}

使用场景

1.简化内部类,内部类可以这样实现了。
这里写图片描述
2.遍历集合

 List<String> list = Arrays.asList("A", "B", "C", "D");    forEach(list, str -> System.out.println(str));    // 也可以写成    forEach(list, System.out::println);