Java8常用的函数式接口

1、Predicate:断言型接口
    
    // 传入的字符串是否以 .sql 结尾
    Predicate<String> isEndWithSql = (s) -> s.endsWith(".sql");

    // 传入的字符串非 .sql 结尾
    Predicate<String> notEndWithSql = isEndWithSql.negate();

    boolean test = isEndWithSql.test("test.sql");
    System.out.println(test);

    boolean test1 = notEndWithSql.test("test.sql");
    System.out.println(test1);

    // 判断集合是否为空
    Predicate<List<String>> isEmptyList = List::isEmpty;

2、Function:功能型接口
    
    // 字符串转为 Integer
    Function<String,Integer> toInteger = s -> Integer.valueOf(s); 

    System.out.println(toInteger.apply("222"));

    toInteger = Integer::valueOf;

    System.out.println(toInteger.apply("222"));


    Function 中的 default 方法:
        andThen:在 Function 执行之后
        compose:在 Function 执行之前

3、Supplier:供给型接口
    
    Supplier<StringBuilder> sbSupplier = StringBuilder::new;

    StringBuilder sb = sbSupplier.get();

4、Consumer:消费型接口

    Consumer<Runnable> runnableConsumer = (run) -> new Thread(run).start();

    runnableConsumer.accept(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {

        }
        System.out.println("测试一下了");
    });

Java8 新增的函数式api存放于 java.util.function 下,提供了大多数常用的函数式接口

Consumer<T> : 消费型接口

Supplier<T> :供给型接口

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

Predicate<T>:断言型接口

public void test(){
    Consumer<String> con = System.out::println;
    con.accept("测试一下了");
}

public void test2(){
    Supplier<Date> sup = Date::new;
	Date date1 = sup.get();
	Date date2 = sup.get();
	System.out.println(date1 == date2);
}

public void test3(){
    Function<Integer,String[]> fun = String[]::new;
	String[] strArr = fun.apply(10);
	System.out.println(strArr);
}

public void test4(){
    Predicate<Integer> predicate = x -> x > 10;
    boolean test = predicate.test(10);
    System.out.println(test);
}

猜你喜欢

转载自blog.csdn.net/now19930616/article/details/86750542
今日推荐