Lambda的使用

案例

  • 使用匿名函数创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("使用匿名函数创建线程");
            }
        }).start();
    }
  • 使用lambda简化创建线程
        new Thread(() -> {
            System.out.println("使用lambda创建线程");
        }).start();

函数式接口 -> 表示接口中只有一个抽象方法的接口并使用注解@FunctionalInterface标识

image.png

四大函数接口认识

1.Consumer<T>

接收一个类型无返回类型
image.png

使用案例

    public static void main(String[] args) {

        testConsumer("haha",str -> {
            System.out.println(str);
        });

        System.out.println("-----------------");
        
        testConsumer("haha",str -> System.out.println(str + str));
    }

    public static void testConsumer(String str,Consumer<String> consumer) {
        consumer.accept(str);
    }

Function<T,R>

T作为参数类型,R作为返回类型

image.png

使用案例

    public static void main(String[] args) {

        /** 返回字符串的长度 */
        int length = testFunction("TestFunction",str -> str.length());
        System.out.println(length);
    }

    public static Integer testFunction(String str,Function<String,Integer> function) {
        return function.apply(str);
    }

Supplier<T>

T作为返回类型

image.png

使用案例

    public static void main(String[] args) {

        /** 获取一个随机值 */
        Double aDouble = testSupplier(() -> Math.random());
        System.out.println(aDouble);

    }


    public static Double testSupplier(Supplier<Double> supplier) {
        return supplier.get();
    }

Predicate<T>

T 作为参数 返回boolean值

image.png

使用案例

    public static void main(String[] args) {
        
        //判断字符串中是否包含字母s
        boolean isContain = testPredicate("String",str -> str.contains("s"));
        
    }

    public static boolean testPredicate(String str,Predicate<String> predicate) {
        return predicate.test(str);
    }
在lambda中如果只有一行代码可以省略{} 以及 需要返回值可以省略 return
只有一个参数可以省略 ()

等风来
1 声望0 粉丝