• Java8新特性 - Lambda表达式


    目录

    一、Lambda表达式

    1.1、为什么使用Lambda表达式?

    1.2、Lambda的标准格式

    Lambda的标准格式

    无参无返回值的Lambda

    有参有返回值的Lambda

    1.3、Lambda的实现原理

    1.4、Lambda省略模式

    1.5、Lambda表达式的前提条件

    1.6、Lambda与匿名内部类对比

    1.7、JDK8接口新增的两个方法

    JDK8接口增强介绍

    接口默认方法的定义格式

    接口默认方法的使用

    接口静态方法的定义格式

    接口静态方法的使用

    接口静态方法与默认方法的区别

    1.8、常用内置函数式接口

    Supplier

    Consumer

    Function

    Predicate

    1.8、方法引用

    Lambda的冗余场景

    常见引用方式

    对象名::引用成员方法

    类名::引用静态方法

    类名::引用实例方法

    类名::new引用构造器

    数组::new引用数组构造器


    一、Lambda表达式

    1.1、为什么使用Lambda表达式?

    Lambda是一个匿名函数,我们可以把Lambda表达式理解为一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。

    匿名内部类与Lambda表达式写法对比:显而易见Lambda表达式更加简便。

    1. public class TestLambda {
    2. public static void main(String[] args) {
    3. //使用匿名内部类
    4. new Thread(new Runnable() {
    5. @Override
    6. public void run() {
    7. System.out.println("普通匿名内部类执行了");
    8. }
    9. }).start();
    10. //使用Lambda
    11. new Thread(()->{
    12. System.out.println("Lambda表达式执行了");
    13. }).start();
    14. }
    15. }

    1.2、Lambda的标准格式

    Lambda的标准格式

    1. (参数类型 参数名称) -> {
    2. 代码体;
    3. }

    无参无返回值的Lambda

    1. public interface Swimmable {
    2. public abstract void swimming();
    3. }
    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. //无参无返回值的Lambda
    4. goSwimming(()->{
    5. System.out.println("无参无返回值的Lambda");
    6. });
    7. }
    8. public static void goSwimming(Swimmable s){
    9. s.swimming();
    10. }
    11. }

    有参有返回值的Lambda

    1. public interface Swimmable {
    2. public abstract int swimming(String name);
    3. }
    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. //有参有返回值的Lambda
    4. goSwimming((String name)->{
    5. System.out.println(name + "正在游泳");
    6. return 10;
    7. });
    8. }
    9. public static void goSwimming(Swimmable s){
    10. s.swimming("尼采");
    11. }
    12. }

    1.3、Lambda的实现原理

    普通的匿名内部类编译后是会生成一个名字带$的类,但Lambda不会生成其它类文件,但是Lambda表达式会在这个类中新生成一个私有的静态方法,并且Lambda表达式的代码会放到这个新增的方法中。同时Lambda底层还是会以普通匿名内部类的形式去展现,只不过在内部类中调用了之前生成的私有的静态方法。

    1.4、Lambda省略模式

    在Lambda标准格式的基础上,使用省略写法的规则为:

    1、小括号内参数的类型可以省略。

    2、如果小括号内有且仅有一个参数,则小括号可以省略。

    3、如果大括号内有且仅有一个语句,可以同时省略大括号、return关键字及语句分号。

    1. public static void main(String[] args) {
    2. List books = new ArrayList<>();
    3. books.add("百年孤独");
    4. books.add("霍乱时期的爱情");
    5. books.add("一桩事先张扬的凶杀案");
    6. books.add("没有人给他写信的上校");
    7. //省略前
    8. books.forEach((t) -> {
    9. System.out.println(t);
    10. });
    11. //省略后
    12. books.forEach(t -> System.out.println(t));
    13. }

            

    1.5、Lambda表达式的前提条件

    1、方法的参数或局部变量类型必须为接口才能使用Lambda。

    2、接口中有且仅有一个抽象方法(函数式接口)。

    1.6、Lambda与匿名内部类对比

    1、所需的类型不一样:

    匿名内部类:需要的类型可以是类、抽象类、接口。

    Lambda:需要的类型必须是接口。

    2、抽象方法的数量不一样:

    匿名内部类:所需的接口中抽象方法的数量随意。

    Lambda:表达式所需的接口只能有一个抽象方法。

    3、实现原理不同:

    匿名内部类:在编译后会形成class。

    Lambda:在程序运行的时候动态生成class。

    1.7、JDK8接口新增的两个方法

    JDK8接口增强介绍

    JDK8以前的接口:

    1. interface 接口名 {
    2. 静态常量;
    3. 抽象方法;
    4. }

    JDK8的接口:

    1. interface 接口名 {
    2. 静态常量;
    3. 抽象方法;
    4. 默认方法;
    5. 静态方法;
    6. }

    接口中的默认方法实现类不需要重写,可以直接使用,实现类也可以根据需要重写。这样就方便接口的扩展。

    接口默认方法的定义格式

    1. interface 接口名 {
    2. public default void method(){
    3. //代码
    4. }
    5. }

    接口默认方法的使用

    1. public interface Swimmable {
    2. public default void eat(String name){
    3. System.out.println(name + "在吃饭");
    4. }
    5. }
    6. class SwimmableImpl implements Swimmable{
    7. }
    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. Swimmable sw = new SwimmableImpl();
    4. sw.eat("马尔克斯");
    5. }
    6. }

    接口静态方法的定义格式

    1. interface 接口名 {
    2. 修饰符 static 返回值类型 方法名(){
    3. //代码
    4. }
    5. }

    接口静态方法的使用

    1. public interface Swimmable {
    2. public static void eat(String name){
    3. System.out.println(name + "在吃饭");
    4. }
    5. }
    6. class SwimmableImpl implements Swimmable{
    7. }
    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. Swimmable.eat("马尔克斯"); //接口的静态方法只能用接口名调用
    4. }
    5. }

    接口静态方法与默认方法的区别

    1、默认方法通过实例调用,静态方法通过接口名调用。

    2、默认方法可以被继承,实现类可以直接使用接口默认方法,也可以重写接口默认方法。

    3、静态方法不能被继承,实现类不能重写接口的静态方法,只能使用接口名调用。

    1.8、常用内置函数式接口

    他们主要在java.util.function包中。下面是最常用的几个接口:

    Supplier

    供给型接口,对应的Lambda表达式需要“对外提供”一个符合泛型类型的数据对象。

    1. @FuncationalInterface
    2. public interface Supplier {
    3. public abstract T get();
    4. }

    实例:返回数组元素最大值

    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. int[] arr = {5,8,1,20,2,17};
    4. printMax(() -> {
    5. Arrays.sort(arr);
    6. return arr[arr.length - 1];
    7. });
    8. }
    9. public static void printMax(Supplier supplier){
    10. int max = supplier.get();
    11. System.out.println(max);
    12. }
    13. }

    Consumer

    与Supplier接口正好相反,它不是生产一个数据,而是消费一个数据。

    1. @FuncationalInterface
    2. public interface Consumer {
    3. public abstract void accept(T t);
    4. }

    实例:将一个字符串转成大写和小写的字符串

    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. printHello((String str) -> {
    4. System.out.println(str.toUpperCase());
    5. });
    6. }
    7. public static void printHello(Consumer consumer){
    8. consumer.accept("hello");
    9. }
    10. }

    Function

    java.util.function.Function接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。有参数有返回值。

    1. @FuncationalInterface
    2. public interface Function {
    3. public abstract R apply(T t);
    4. }

    实例:将字符串转成数字

    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. getNumber((String str) -> {
    4. Integer i = Integer.parseInt(str);
    5. return i;
    6. });
    7. }
    8. public static void getNumber(Function function){
    9. Integer num = function.apply("10");
    10. System.out.println(num);
    11. }
    12. }

    Predicate

    有时候我们需要对某种类型进行判断,从而得到一个boolean值结果。

    1. @FuncationalInterface
    2. public interface Predicate {
    3. public abstract boolean test(T t);
    4. }

    实例1:判断一个人名如果超过3个字就认为是很长的名字

    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. isLongName((String name) -> {
    4. return name.length() > 3;
    5. });
    6. }
    7. public static void isLongName(Predicate predicate){
    8. boolean b = predicate.test("马尔克斯");
    9. System.out.println(b);
    10. }
    11. }

    实例2:判断一个字符串中包含W,也包含H

    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. exercise((String str) -> {
    4. return str.contains("H");
    5. },(String str) -> {
    6. return str.contains("W");
    7. });
    8. }
    9. public static void exercise(Predicate p1,Predicate p2){
    10. boolean b1 = p1.test("Hello");
    11. boolean b2 = p2.test("World");
    12. if(b1 && b2){
    13. System.out.println("既包含W,也包含H");
    14. }
    15. }
    16. }

    使用and可以将代码改写为:

    1. public class TestLambda2 {
    2. public static void main(String[] args) {
    3. exercise((String str) -> {
    4. return str.contains("H");
    5. },(String str) -> {
    6. return str.contains("W");
    7. });
    8. }
    9. public static void exercise(Predicate p1,Predicate p2){
    10. String str = "HelloWorld";
    11. boolean b = p1.and(p2).test(str);
    12. if(b)
    13. System.out.println("既包含W,也包含H");
    14. }
    15. }

    1.8、方法引用

    Lambda的冗余场景

    1. public class Y {
    2. public static void main(String[] args) {
    3. //使用方法引用
    4. //这个指定的方法getMax去重写接口的抽象方法accept,到时候调用接口的抽象方法就是调用传递过去的方法
    5. printMax(Y::getMax);
    6. }
    7. public static void getMax(int[] arr){
    8. int sum = 0;
    9. for (int n : arr){
    10. sum += n;
    11. }
    12. System.out.println(sum);
    13. }
    14. public static void printMax(Consumer<int[]> consumer){
    15. int[] arr = {11,22,33,44,55};
    16. consumer.accept(arr);
    17. }
    18. }

    常见引用方式

    1、对象::方法名

    2、类名::静态方法

    3、类名::普通方法

    4、类名::构造器

    5、String[]::数组构造器

    对象名::引用成员方法

    1. //正常使用Lambda
    2. @Test
    3. public void test01(){
    4. Date now = new Date();
    5. Supplier su1 = () -> {
    6. return now.getTime();
    7. };
    8. Long aLong = su1.get();
    9. System.out.println(aLong);
    10. }
    11. //对象引用Lambda
    12. @Test
    13. public void test02(){
    14. Date now = new Date();
    15. Supplier su2 = now::getTime;
    16. Long aLong = su2.get();
    17. System.out.println(aLong);
    18. }

    注意:你调用方法的参数和返回值要和接口中抽象方法的返回值和参数要一致比如上述代码,getTime()方法参数是无参,返回值是Long类型,那我们接口中的get()方法也是一样的。


    类名::引用静态方法

    1. @Test
    2. public void test01(){
    3. Supplier sup = System::currentTimeMillis;
    4. Long aLong = sup.get();
    5. System.out.println(aLong);
    6. }

    类名::引用实例方法

    Java面向对象中,类名只能调用静态方法,类名引用实例方法是有前提的,实际上是拿第一个参数作为方法的调用者。

    当调用的方法无参时:

    1. @Test
    2. public void test01(){
    3. Function fun = String::length;
    4. Integer length = fun.apply("Hello");
    5. System.out.println(length);
    6. }

    当方法有一个参数时:

    1. @Test
    2. public void test02(){
    3. BiFunction fun = String::substring;
    4. String result = fun.apply("HelloWorld", 3);
    5. System.out.println(result);
    6. }

    类名::new引用构造器

    由于构造器的名称与类名完全一样,所以构造器引用使用类名称::new的格式表示。

    1. @Test
    2. public void test01(){
    3. Supplier sup = Person::new;
    4. Person person = sup.get();
    5. System.out.println(person);
    6. }

    数组::new引用数组构造器

    数组也是Object的子类对象,所以同样具有构造器,只是语法稍有不同。

    1. @Test
    2. public void test01(){
    3. Functionint[]> fun = int[]::new;
    4. int[] apply = fun.apply(5);
    5. System.out.println(apply);
    6. }
  • 相关阅读:
    VOIP语音抓包、解码与带宽计算
    算法模型总结:字符串
    面向大规模队列,百万并发的多优先级消费系统设计
    【Filament】纹理贴图
    避免数据泄露风险!NineData提供SQL开发规范和用户访问量管理
    Nacos服务发现数据模型
    AcWing 4505. 最大子集
    基于java的购物中心商铺管理系统的设计与实现/商铺管理系统
    Python使用opencv实现图片定位第三种方式
    react-starter脚手架搭建过程
  • 原文地址:https://blog.csdn.net/qq_38196449/article/details/132690686