前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >02-Java8新特性 函数式接口

02-Java8新特性 函数式接口

作者头像
彼岸舞
发布2021-12-14 19:46:42
3120
发布2021-12-14 19:46:42
举报

函数式接口

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

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

内置四大核心函数式接口

Consumer 消费型接口

void accept(T t);

代码语言:javascript
复制
@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();

代码语言:javascript
复制
@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);

代码语言:javascript
复制
@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);

代码语言:javascript
复制
@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 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 函数式接口
  • 内置四大核心函数式接口
    • Consumer 消费型接口
      • Supplier 供给型接口
        • Function<T,R> 函数型接口
          • Predicate 断言型接口
            • 其他接口
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档