当前位置: 首页 > news >正文

Java 8 - Lambda 表达式

1. 函数式接口

        当一个接口中只有一个非 default 修饰的方法,这个接口就是一个函数式接口用

@FunctionalInterface 标注

1)只有一个抽象方法

@FunctionalInterface
public interface MyInterface {void print(int x);
}

2)只有一个抽象方法和一个 default 方法

@FunctionalInterface
public interface MyInterface {void print(int x);// 1.8 之后接口可以有默认实现方法default String getValue(){return "value";}
}

3)只有一个抽象方法和多个 default 方法

@FunctionalInterface
public interface MyInterface {void print(int x);// 1.8 之后接口可以有默认实现方法default String getValue(){return "value";}default int getAge(int age){return age;}
}

2. 使用 lambda 表达式返回函数式接口对象

        当使用函数式接口中的的唯一非 default 方法时,传统的做法是先写一个接口的实现类,给出接口中抽象方法的具体实现,然后 new 一个该类的实例化对象,在调用重写后的方法,步骤比较繁琐,lambda 可以快速实现该方法的实现和调用

创建一个接口

@FunctionalInterface
public interface MyInterface {void print(int x);// 1.8 之后接口可以有默认实现方法default String getValue(){return "value";}
}

使用 lambda 表达式返回一个该接口对象,并给出该方法的具体实现

public class MyClass {public static void main(String[] args) {MyInterface myinterface = x -> System.out.println("x ="+ x);myinterface.print(12344);}
}

lambda 表达式语法

语法格式: () -> {};# () 中代表的是接口中抽象方法的参数值
# {} 中代表该方法的具体实现
# () -> {}; 的返回值是接口的一个实例化对象

3. Runnable 接口

        Runnable 接口是用来创建线程的一个接口,是一个典型的函数式接口

  源码如下:

 

   通过 Lambda 表达式创建线程

public class Test1{public static void main(String[] args) {Runnable runnable = () -> System.out.println("this a thread");runnable.run();}
}

4. Callable 接口

  Callable 接口是用来创建线程的一个接口,是一个典型的函数式接口

  源码如下:

  通过 Lambda 表达式创建线程

public class MyCallable {public static void main(String[] args) throws Exception {Callable<Integer> callable = () -> {System.out.println("this a thread");return  1;};callable.call();}
}

http://www.lryc.cn/news/45037.html

相关文章:

  • 【Ruby学习笔记】4.Ruby 类和对象及类案例
  • 分享一个计算表格内单元格合并的工具,支持行合并、列合并等常见场景
  • CUDA编程(三):Hello world
  • 二十九、String的不可变性
  • TCP服务器如何使用select处理多客户连接
  • python字符编码
  • 面向对象练习题(8)
  • 重构类关系-Extract Interface提炼接口八
  • vivo手机各系列简介和拆解
  • Redis:redis通用命令;redis常见数据结构;redis客户端;redis的序列化
  • Java新特性
  • Java_Spring:8. Spring 中 AOP 的细节
  • uni-app--》uni-app的生命周期讲解
  • fastp软件介绍
  • C++继承相关总结
  • 【从零开始学习 UVM】8.2、Reporting Infrastructure —— uvm_printer 详解
  • Mybatis、TKMybatis对比
  • 37了解高可用技术方案,如冗余、容灾
  • jdb调试问题集锦
  • 要和文心一言来一把你画我猜吗?
  • delete[] p->elems和free(p->elems)有什么区别?
  • CAS问题
  • 网络编程socket(下)
  • 华为OD机试题【打折买水果】用 C++ 编码,速通
  • JSON 数据类型
  • Python函数简介
  • 一文读懂 mysql 为什么要两阶段提交以及两阶段提交原理
  • 启动Hadoop报错【Error: JAVA_HOME is not set and could not be found.】
  • 《MySQL系列-InnoDB引擎35》索引与算法-B+树索引的使用
  • 【EHub_tx1_tx2_E100】不止科技NVISTAR ROC 300激光雷达Ubuntu18.04+ROS1ROS2 评测