方法引用与构造方法引用

2024-06-03 05:20
文章标签 方法 引用 构造方法

本文主要是介绍方法引用与构造方法引用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

方法引用

什么是方法引用

构造方法引用

构造方法引用(也可以称作构造器引用)

数组构造方法引用


方法引用

什么是方法引用

当要传递给 Lambda 体的操作,已经有实现的方法了,可以使用方法引用。

方法引用可以看做是 Lambda 表达式深层次的表达。换句话说,方法引用就是 Lambda 表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是 Lambda 表达式的一个语法糖。

要求:实现接口的抽象方法的参数类列和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致。

格式:使用操作符 :: 将类(或者对象)与方法名分割开来

如下三种主要使用情况:

  • 对象 :: 实例方法名
  • 类 :: 静态方法名
  • 类 :: 实例方法名

示例

public class Person {private String name;private LocalDate birthday;public Person() {}public Person(String name) {this.name = name;}public Person(String name, LocalDate birthday) {this.name = name;this.birthday = birthday;}public String getName() {return name;}public void setName(String name) {this.name = name;}public LocalDate getBirthday() {return birthday;}public void setBirthday(LocalDate birthday) {this.birthday = birthday;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", birthday=" + birthday +'}';}public static int compareByAge(Person a, Person b) {return a.birthday.compareTo(b.birthday);}
}
public class MethodReferences {//情况一:对象 :: 实例方法//Consumer 中的 void accept(T t) 与 PrintStream 中的 void println(T t)@Testpublic void t1() {//原来的写法Consumer<String> consumer = new Consumer<String>() {@Overridepublic void accept(String s) {System.out.println(s);}};consumer.accept("上海市");//lambda 写法Consumer<String> consumerL = str -> System.out.println(str);consumerL.accept("上海");//方法引用PrintStream out = System.out;Consumer<String> consumerM = out::println;consumerM.accept("shanghai");}//Supplier 中的 T get() 与 Person 中的 String getName()@Testpublic void t2() {Person person = new Person("小威", LocalDate.of(2016, 9, 1));//原来的写法Supplier<String> supplier = new Supplier<String>() {@Overridepublic String get() {return person.getName();}};System.out.println(supplier.get());//lambda 写法Supplier<String> supplierL = () -> person.getName();System.out.println(supplierL.get());// 方法引用Supplier<String> supplierM = person::getName;System.out.println(supplierM.get());}
//======================================================================================================================//情况二:类 :: 静态方法//Comparator 中的 int compare(T t1,T t2) 与 Integer 中的 int compare(T t1,T t2)@Testpublic void t3() {//原来的写法Comparator<Integer> comparator = new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return Integer.compare(o1, o2);}};System.out.println(comparator.compare(520, 1314));//lambda 写法Comparator<Integer> comparatorL = (o1, o2) -> Integer.compare(o1, o2);System.out.println(comparatorL.compare(100, 99));// 方法引用Comparator<Integer> comparatorM = Integer::compareTo;System.out.println(comparatorM.compare(123, 321));}//Function 中 R apply(T t) 与 Math 中 Long round(Double d)@Testpublic void t4() {//原来的写法Function<Double, Long> function = new Function<Double, Long>() {@Overridepublic Long apply(Double aDouble) {return Math.round(aDouble);}};System.out.println(function.apply(13.7));//lambda 写法Function<Double, Long> functionL = d -> Math.round(d);System.out.println(functionL.apply(13.4));// 方法引用Function<Double, Long> functionM = Math::round;System.out.println(functionM.apply(13.9));}
//======================================================================================================================//情况三:类 :: 实例方法(有难度)//Comparator 中的 int compare(T t1,T t2) 与 String 中的 int t1.compareTo(t2)@Testpublic void t5() {//原来的写法Comparator<String> comparator = new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return o1.compareTo(o2);}};System.out.println(comparator.compare("abc", "abd"));//lambda 写法Comparator<String> comparatorL = (o1, o2) -> o1.compareTo(o2);System.out.println(comparatorL.compare("abc", "abd"));// 方法引用Comparator<String> comparatorM = String::compareTo;System.out.println(comparatorM.compare("abd", "abc"));}//BiPredicate 中的 boolean test(T t1,T t2) 与 String 中的 boolean t1.equals(t2)@Testpublic void t6() {//原来的写法BiPredicate<String, String> biPredicate = new BiPredicate<String, String>() {@Overridepublic boolean test(String s, String s2) {return s.equals(s2);}};System.out.println(biPredicate.test("abc", "abd"));//lambda 写法BiPredicate<String, String> biPredicateL = (s1, s2) -> s1.equals(s2);System.out.println(biPredicateL.test("abc", "abd"));// 方法引用BiPredicate<String, String> biPredicateM = String::equals;System.out.println(biPredicateM.test("abc", "abd"));}//Function 中的 R apply(T t) 与 Person 中的 String getName()@Testpublic void t7() {Person person = new Person("Vincent", LocalDate.of(1991, 1, 28));//原来的写法Function<Person, String> function = new Function<Person, String>() {@Overridepublic String apply(Person person) {return person.getName();}};System.out.println(function.apply(person));//lambda 写法Function<Person, String> functionL = p -> p.getName();System.out.println(functionL.apply(person));// 方法引用Function<Person, String> functionM = Person::getName;System.out.println(functionM.apply(person));}
}

 

构造方法引用

构造方法引用又分构造方法引用和数组构造方法引用。

构造方法引用(也可以称作构造器引用)

组成语法格式:Class::new

构造函数本质上是静态方法,只是方法名字比较特殊,使用的是 new 关键字

要求:和方法引用类似,函数接口的抽象方法的形参列表和构造器的形参列表一致,且抽象方法的返回值类型即为构造器所属的类的类型。

示例:

String::new, 等价于 lambda 表达式 () -> new String()

public class ConstructorReferences {//构造器引用//Supplier 中的 T get() 与 Person()@Testpublic void t1() {//原来的写法Supplier<Person> supplier = new Supplier<Person>() {@Overridepublic Person get() {return new Person();}};System.out.println(supplier.get());//lambda的写法Supplier<Person> supplierL = () -> new Person();System.out.println(supplierL.get());//构造器引用Supplier<Person> supplierM = Person::new;System.out.println(supplierM.get());}//Function 中的 R apply(T t)@Testpublic void t2() {//原来的写法Function<String, Person> function = new Function<String, Person>() {@Overridepublic Person apply(String s) {return new Person(s);}};System.out.println(function.apply("小微"));//lambda的写法Function<String, Person> functionL = s -> new Person(s);System.out.println(functionL.apply("小微"));//构造器引用Function<String, Person> functionM = Person::new;System.out.println(functionM.apply("小微"));}//BiFunction 中的 apply(T t,U u)@Testpublic void t3() {//原来的写法BiFunction<String, LocalDate, Person> biFunction = new BiFunction<String, LocalDate, Person>() {@Overridepublic Person apply(String s, LocalDate localDate) {return new Person(s, localDate);}};Person person = biFunction.apply("威仔", LocalDate.of(2010, 12, 13));System.out.println(person);//lambda的写法BiFunction<String, LocalDate, Person> biFunctionL = (s, lD) -> new Person(s, lD);Person personL = biFunctionL.apply("威仔", LocalDate.of(2010, 12, 13));System.out.println(personL);//构造器引用BiFunction<String, LocalDate, Person> biFunctionM = Person::new;Person personM = biFunctionM.apply("威仔", LocalDate.of(2010, 12, 13));System.out.println(personM);}
}

 

数组构造方法引用

组成语法格式:TypeName[]::new

要求:可以把数组看做事一个特殊的类,则写法与构造器引用一致。

示例:

String[]::new 是一个含有一个参数的构造器引用,这个参数就是数组的长度。等价于 lambda 表达式 x -> new String[x]

public class ConstructorReferences {//数组引用//Function 中的 R apply(T t)@Testpublic void t4() {//原来的写法Function<Integer, String[]> function = new Function<Integer, String[]>() {@Overridepublic String[] apply(Integer integer) {return new String[integer];}};String[] apply = function.apply(10);System.out.println(Arrays.toString(apply));//lambda的写法Function<Integer, String[]> functionL = length -> new String[length];String[] applyL = functionL.apply(10);System.out.println(Arrays.toString(applyL));//数组引用Function<Integer, String[]> functionM = String[]::new;String[] applyM = function.apply(10);System.out.println(Arrays.toString(applyM));}
}

这篇关于方法引用与构造方法引用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1026112

相关文章

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤

在Golang中实现定时任务的几种高效方法

《在Golang中实现定时任务的几种高效方法》本文将详细介绍在Golang中实现定时任务的几种高效方法,包括time包中的Ticker和Timer、第三方库cron的使用,以及基于channel和go... 目录背景介绍目的和范围预期读者文档结构概述术语表核心概念与联系故事引入核心概念解释核心概念之间的关系

在Linux终端中统计非二进制文件行数的实现方法

《在Linux终端中统计非二进制文件行数的实现方法》在Linux系统中,有时需要统计非二进制文件(如CSV、TXT文件)的行数,而不希望手动打开文件进行查看,例如,在处理大型日志文件、数据文件时,了解... 目录在linux终端中统计非二进制文件的行数技术背景实现步骤1. 使用wc命令2. 使用grep命令

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到

XML重复查询一条Sql语句的解决方法

《XML重复查询一条Sql语句的解决方法》文章分析了XML重复查询与日志失效问题,指出因DTO缺少@Data注解导致日志无法格式化、空指针风险及参数穿透,进而引发性能灾难,解决方案为在Controll... 目录一、核心问题:从SQL重复执行到日志失效二、根因剖析:DTO断裂引发的级联故障三、解决方案:修复

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee

Java继承映射的三种使用方法示例

《Java继承映射的三种使用方法示例》继承在Java中扮演着重要的角色,它允许我们创建一个类(子类),该类继承另一个类(父类)的所有属性和方法,:本文主要介绍Java继承映射的三种使用方法示例,需... 目录前言一、单表继承(Single Table Inheritance)1-1、原理1-2、使用方法1-