02-Java8新特性 函数式接口

函数式接口

接口中只有一个抽象方法的口,称为函数式接口,可以使用注解@FunctionInterface 修饰

@FunctionInterface : 可以检查接口是否为函数式接口

内置四大核心函数式接口

Consumer 消费型接口

void accept(T t);

@Test
public void test5(){
    happy("hello world", str -> System.out.println("this is " + str));
}

public void happy(String str, Consumer consumer){
    consumer.accept(str);
}

Supplier 供给型接口

T get();

@Test
public void test6(){
    List num = getNum(10, () -> (int) (Math.random() * 100));
    num.forEach(System.out::println);
}

public List getNum(int num, Supplier supplier){
    ArrayList integers = new ArrayList<>();
    for (int i = 0; i < num; i++) {
        integers.add(supplier.get());
    }
    return integers;
}

Function<T,R> 函数型接口

R apply(T t);

@Test
public void test7(){
    String hello_world = stringHandler("hello world", s -> s.substring(0, 5));
    System.out.println(hello_world);
}

public String stringHandler(String string, Function<String,String> function){
    return function.apply(string);
}

Predicate 断言型接口

boolean test(T t);

@Test
public void test8(){
    boolean query = isQuery("select query", s -> s.equals("select query"));
    System.out.println(query);
}

public boolean isQuery(String string, Predicate predicate){
    return predicate.test(string);
}

其他接口

作者:彼岸舞

时间:2021\12\13

内容关于:Java

本文属于作者原创,未经允许,禁止转发

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值