资讯专栏INFORMATION COLUMN

深入理解 lambda表达式 与 MethodReference(四)

EasonTyler / 2706人阅读

摘要:陈杨一测试数据准备二方法引用引入方法引用集合遍历集合遍历集合遍历集合遍历三什么是

package com.java.design.java8.MethodReference;


import com.java.design.java8.entity.Student;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;


/**
 * @author 陈杨
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MethodReference {
一、测试数据准备
private List students;
private List snames;

private Student studentSupplier(Supplier studentSupplier) {
    return studentSupplier.get();
}


//    private StudentConstructor studentConstructor =
//            (id, name, sex, age, addr, salary) ->
//                    new Student(id, name, sex, age, addr, salary);

private StudentConstructor studentConstructor = Student::new;

private Student studentAllArgs(Integer id, String name, String sex, Integer age, String addr, Double salary) {

    return studentConstructor.studentAllArgs(id, name, sex, age, addr, salary);
}

@Before
public void init() {

    Student kirito =
            new Student(1, "Kirito", "Male", 18, "Sword Art Online", 999999999.0);
    Student Asuna =
            new Student(2, "Asuna", "Female", 17, "Sword Art Online", 999999999.0);
    Student Sinon =
            new Student(3, "Sinon", "Female", 16, "Gun Gale Online", 999999999.0);
    Student Yuuki =
            new Student(4, "Yuuki", "Female", 15, "Alfheim Online", 999999999.0);
    Student Alice =
            new Student(5, "Alice", "Female", 14, "Alicization", 999999999.0);

    students = Arrays.asList(kirito, Asuna, Sinon, Yuuki, Alice);

    snames = Arrays.asList("kirito", "Asuna", "Sinon", "Yuuki", "Alice");

}
二、方法引用 引入
@Test
public void testMethodReference() {


    //  MethodReference 方法引用
    List Iloveyou = Arrays.asList("Kirito", "Love", "Asuna");

    //集合遍历 Lambda
    System.out.println("---------------------------------------
");
    System.out.println("集合遍历 Lambda");
    Iloveyou.forEach(str -> System.out.println(str));


    //集合遍历 MethodReference
    System.out.println("---------------------------------------
");
    System.out.println("集合遍历 MethodReference");
    Iloveyou.forEach(System.out::println);
三、什么是方法引用
//  MethodReference
//  方法引用是Lambda表达式的特殊替换
//  方法引用本质是一个 函数指针 Function Pointer
//  这个指针指向被引用方法
//  eg: 方法引用System.out::println 指向System.out.println()这个函数
四、方法引用的分类

1、 静态方法引用

//   1、 静态方法引用

//   静态方法引用 类名::静态方法名
//   静态方法引用 功能实现等价于 调用 类的静态方法

//   静态方法引用 与 调用  无任何关系
//          类名.静态方法名   -->方法调用  显示传参
//          类名::静态方法名  -->方法引用  隐式传参  编译器自动推断  方法引用的表达式 函数指针 指向 被引用函数
System.out.println("---------------------------------------
");
System.out.println(" 静态方法引用 按年龄排序");
students.sort(StaticStudentComparator::staticCompareStudentByAge);
students.forEach(System.out::println);

System.out.println("---------------------------------------
");
System.out.println(" 静态方法引用 按姓名排序");
students.sort(StaticStudentComparator::staticCompareStudentByName);
students.forEach(System.out::println);

2、 对象实例方法引用

//   2、 对象实例方法引用

//   对象实例方法引用 引用名(对象名)::实例方法名
//   对象实例方法引用 功能实现等价于 调用 对象实例 所拥有的 实例方法
StudentComparator studentComparator = new StudentComparator();
System.out.println("---------------------------------------
");
System.out.println(" 静态方法引用 按年龄排序");
students.sort(studentComparator::compareStudentByAge);
students.forEach(System.out::println);


System.out.println("---------------------------------------
");
System.out.println(" 对象实例方法引用 按姓名排序");
students.sort(studentComparator::compareStudentByName);
students.forEach(System.out::println);

3、 类实例方法引用

//   3、 类实例方法引用
//   类实例方法引用 类名::实例方法名

System.out.println("---------------------------------------
");
System.out.println(" 类实例方法引用 按年龄排序");
students.sort(Student::classCompareStudentByAge);
students.forEach(System.out::println);

System.out.println("---------------------------------------
");
System.out.println(" 类实例方法引用 按姓名排序");
students.sort(Student::classCompareStudentByName);
students.forEach(System.out::println);

System.out.println("---------------------------------------
");
System.out.println(" 类实例方法引用 容易理解的 字符串排序");
snames.sort(String::compareToIgnoreCase);
snames.forEach(System.out::println);

4、 构造方法引用

//  4、  构造方法引用
//  构造方法引用 类名::new
//  注意: 实体类Student 事先 有定义好的 全参构造方法 与无参构造方法
//        若没有构造方法 需要自行添加 否则报错
//  Student::new 可以根据参数不同 对构造方法进行自动识别 重载

//  利用无参构造方法构造studentNoArgs对象
System.out.println("---------------------------------------
");
System.out.println("利用无参构造方法构造studentNoArgs对象");
Student studentNoArgs = this.studentSupplier(Student::new);
System.out.println(studentNoArgs);

//  利用自定义全参构造方法构造student对象
System.out.println("---------------------------------------
");
System.out.println("利用全参构造方法构造studentNoArgs对象");
Student Silica = this.studentAllArgs
        (6, "Silica", "Female", 10, "Sword Art Online", 999999999.0);
System.out.println(Silica);


    }
}
五、StaticStudentComparator类 (静态方法实例引用)
import com.java.design.java8.entity.Student;

import java.util.Comparator;

public class StaticStudentComparator {


    static Comparator studentAgeComparator =
            (first, last) -> first.getAge() - last.getAge();

    static Comparator studentNameComparator =
            (first, last) -> first.getName().compareToIgnoreCase(last.getName());


    public static int staticCompareStudentByAge(Student first, Student last) {

        return studentAgeComparator.compare(first, last);
    }


    public static int staticCompareStudentByName(Student first, Student last) {

        return studentNameComparator.compare(first, last);
    }


}
六、StudentComparator类 (对象方法实例引用)
import com.java.design.java8.entity.Student;

import java.util.Comparator;

public class StudentComparator {


    Comparator studentAgeComparator =
            (first, last) -> first.getAge() - last.getAge();

    Comparator studentNameComparator =
            (first, last) -> first.getName().compareToIgnoreCase(last.getName());


    public int compareStudentByAge(Student first, Student last) {

        return studentAgeComparator.compare(first, last);
    }


    public int compareStudentByName(Student first, Student last) {

        return studentNameComparator.compare(first, last);
    }

}
七、StudentConstructor @FunctionalInterface接口 (构造方法实例引用)
import com.java.design.java8.entity.Student;

@FunctionalInterface
public interface StudentConstructor {


    Student studentAllArgs(Integer id, String name, String sex, Integer age, String addr, Double salary);


}
八 、Student实体类 (类实例方法引用)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    private Integer id;

    private String name;

    private String sex;

    private Integer age;

    private String addr;

    private Double salary;

    public int classCompareStudentByAge(Student student) {

        return this.getAge() - student.getAge();
    }

    public int classCompareStudentByName(Student student) {

        return this.getName().compareToIgnoreCase(student.getName());
    }
}
九、 测试结果
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-02 17:04:20.851  INFO 16876 --- [           main] c.j.d.j.MethodReference.MethodReference  : Starting MethodReference on DESKTOP-87RMBG4 with PID 16876 (started by 46250 in E:IdeaProjectsdesign)
2019-02-02 17:04:20.852  INFO 16876 --- [           main] c.j.d.j.MethodReference.MethodReference  : No active profile set, falling back to default profiles: default
2019-02-02 17:04:21.422  INFO 16876 --- [           main] c.j.d.j.MethodReference.MethodReference  : Started MethodReference in 0.878 seconds (JVM running for 1.682)
---------------------------------------

集合遍历 Lambda
Kirito
Love
Asuna
---------------------------------------

集合遍历 MethodReference
Kirito
Love
Asuna
---------------------------------------

 静态方法引用 按年龄排序
Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)
Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8)
Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8)
Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8)
Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)
---------------------------------------

 静态方法引用 按姓名排序
Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)
Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8)
Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)
Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8)
Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8)
---------------------------------------

 静态方法引用 按年龄排序
Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)
Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8)
Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8)
Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8)
Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)
---------------------------------------

 对象实例方法引用 按姓名排序
Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)
Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8)
Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)
Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8)
Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8)
---------------------------------------

 类实例方法引用 按年龄排序
Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)
Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8)
Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8)
Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8)
Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)
---------------------------------------

 类实例方法引用 按姓名排序
Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)
Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8)
Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)
Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8)
Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8)
---------------------------------------

 类实例方法引用 容易理解的 字符串排序
Alice
Asuna
kirito
Sinon
Yuuki
---------------------------------------

利用无参构造方法构造studentNoArgs对象
Student(id=null, name=null, sex=null, age=null, addr=null, salary=null)
---------------------------------------

利用全参构造方法构造studentNoArgs对象
Student(id=6, name=Silica, sex=Female, age=10, addr=Sword Art Online, salary=9.99999999E8)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77392.html

相关文章

  • Java8: Functional Interface and Lambda Expression

    摘要:写在前面最近在看实战感觉这本书的排版纸质内容真的都超级棒个人觉得这本书还是很值得一读本文简单或详细介绍一下的和表达式函数式接口是在才开始引入的首先看一下普通接口和函数式接口的区别普通接口指的是一些具有相同属性和行为的类的抽象函数式接口也是同 写在前面: 最近在看,感觉这本书的排版,纸质,内容真的都超级棒,个人觉得这本书还是很值得一读.本文简单或详细介绍一下Java8的Functiona...

    sunnyxd 评论0 收藏0
  • 《Java8实战》-第三章读书笔记(Lambda达式-01)

    摘要:之前,使用匿名类给苹果排序的代码是的,这段代码看上去并不是那么的清晰明了,使用表达式改进后或者是不得不承认,代码看起来跟清晰了。这是由泛型接口内部实现方式造成的。 # Lambda表达式在《Java8实战》中第三章主要讲的是Lambda表达式,在上一章节的笔记中我们利用了行为参数化来因对不断变化的需求,最后我们也使用到了Lambda,通过表达式为我们简化了很多代码从而极大地提高了我们的...

    longshengwang 评论0 收藏0
  • 好文章必读 - 收藏集 - 掘金

    摘要:方法即为收集器,它接收高阶函数和的后端掘金年的第一天,我坐在独墅湖边,写下这篇文章。正因如此,所以最全系列教程后端掘金是从版本开始引入的一个新的,可以替代标准的。 设计模式之单例模式 - 掘金前言 作为一个好学习的程序开发者,应该会去学习优秀的开源框架,当然学习的过程中不免会去阅读源码,这也是一个优秀程序员的必备素养,在学习的过程中很多人会遇到的障碍,那就是设计模式。很多优秀的框架会运...

    FrozenMap 评论0 收藏0
  • 深入理解JAVA语言

    摘要:在那里,可以理解为指针。局部变量不能够被访问控制符及修饰都可以被修饰变量的传递与语言相似调用对象方法时要传递参数。内部类内部类是所在类的成员。大体上相当于其他语言的匿名函数或函数指针。 1. 变量及其传递 基本类型变量(primitive type)和引用类型变量(reference type) 基本类型(primitive type):其值直接存于变量中。在这里 引用型(refer...

    PumpkinDylan 评论0 收藏0

发表评论

0条评论

EasonTyler

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<