欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java8新特性:Lambda表达式之方法引用详解

程序员文章站 2022-03-15 08:24:51
1.方法引用简述方法引用是用来直接访问类或者实例的已经存在的方法或者构造方法。方法引用提供了一种引用而不执行方法的方式,它需要由兼容的函数式接口构成的目标类型上下文。计算时,方法引用会创建函数式接口的...

1.方法引用简述

方法引用是用来直接访问类或者实例的已经存在的方法或者构造方法。方法引用提供了一种引用而不执行方法的方式,它需要由兼容的函数式接口构成的目标类型上下文。计算时,方法引用会创建函数式接口的一个实例。

当lambda表达式中只是执行一个方法调用时,不用lambda表达式,直接通过方法引用的形式可读性更高一些。方法引用是一种更简洁易懂的lambda表达式。

lambda表达式全文详情地址:http://blog.csdn.net/sun_promise/article/details/51121205

2.作用

方法引用的唯一用途是支持lambda的简写。

方法引用提高了代码的可读性,也使逻辑更加清晰。(优点)

3.组成

使用::操作符将方法名和对象或类的名字分隔开。

“::” 是域操作符(也可以称作定界符、分隔符)。

eg:

Java8新特性:Lambda表达式之方法引用详解

4.分类

1)静态方法引用

组成语法格式:classname::staticmethodname

note:

  • 静态方法引用比较容易理解,和静态方法调用相比,只是把 . 换为 ::
  • 在目标类型兼容的任何地方,都可以使用静态方法引用。

eg:

-- string::valueof   等价于lambda表达式 (s) -> string.valueof(s)

-- math::pow       等价于lambda表达式  (x, y) -> math.pow(x, y);

-- 假设需要从一个数字列表中找出最大的一个数字。

方法引用方式:

(max是一collections里的一个静态方法,它需要传入一个list类型的参数。)

function<list<integer>, integer> maxfn =collections::max;

maxfn.apply(arrays.aslist(1, 10, 3, 5))。

上面 等价于lambda表达式 function<list<integer>, integer> maxfn = (numbers) -> collections.max(numbers);。

--  以字符串反转为例:

/*
* 函数式接口
* */
interface stringfunc {
 string func(string n);
}
class mystringops {
 //静态方法: 反转字符串
 public static string strreverse(string str) {
 string result = "";
 for (int i = str.length() - 1; i >= 0; i--) {
  result += str.charat(i);
 }
 return result;
 }
}
class methodrefdemo {
 public static string stringop(stringfunc sf, string s) {
 return sf.func(s);
 }
 public static void main(string[] args) {
 string instr = "lambda add power to java";
 //mystringops::strreverse 相当于实现了接口方法func() ,并在接口方法func()中作了mystringops.strreverse()操作
 string outstr = stringop(mystringops::strreverse, instr);
 system.out.println("original string: " + instr);
 system.out.println("string reserved: " + outstr);
 }
}

输出结果:

original string: lambda add power to java
string reserved: avaj ot rewop dda adbmal

分析:

在程序中,特别注意下面这行代码:string outstr = stringop(mystringops::strreverse, instr);

其中将对mystringops内声明的静态方法strreverse()的引用传递给stringop()方法的第一个参数。可以这么做,因为
strreverse与stringfunc函数式接口兼容。因此,表达式mystringops::strreverse的计算结果为对象引用,其中,
strreverse提供了stringfunc的func()方法的实现。

--  找到列表中具有最大值的对象

(找到集合中最大元素的一种方法是使用collections类定义的max()方法。对于这里使用的max()版本,必须传递一个集合引用,以及一个实现了comparator<t>接口的对象的实例。comparator<t>接口指定如何比较两个对象,它只定义了抽象方法compare(),该方法接受两个参数,其类型均为要比较的对象的类型。如果第一个参数大于第二个参数,该方法返回一个正数;如果两个参数相等,返回0;如果第一个参数小于第二个参数,返回一个负数。

过去,要在max()方法中使用用户定义的对象,必须首先通过一个类显式实现comparator<t>接口,然后创建该类的一个实例,通过这种方法获得comparator<t>接口的一个实例,然后,把这个实例作为比较器传递给max()方法。在jdk 8中,现在可以简单地将比较方法的引用传递给max()方法,因为这将自动实现比较器。)

class myclass {
 private int val;
 myclass(int v) {
 val = v;
 }
 public int getvalue() {
 return val;
 }
}
class usemethodref {
 public static int comparemc(myclass a, myclass b) {
 return a.getvalue() - b.getvalue();
 }
 public static void main(string[] args) {
 arraylist<myclass> a1 = new arraylist<myclass>();
 a1.add(new myclass(1));
 a1.add(new myclass(4));
 a1.add(new myclass(2));
 a1.add(new myclass(9));
 a1.add(new myclass(3));
 a1.add(new myclass(7));
 //usemethodref::comparemc生成了抽象接口comparator定义的compare()方法的实例。
 myclass maxvalobj = collections.max(a1, usemethodref::comparemc);
 system.out.println("maximum value is: " + maxvalobj.getvalue());
 }
}

输出结果:

maximum value is: 9

分析:

在程序中,注意myclass即没有定义自己的比较方法,也没有实现comparator接口。但是,通过调用max()方法,仍然可以获得myclass对象列表中的最大值,这是因为usemethodref定义了静态方法comparemc(),它与comparator定义的compare()方法兼容。因此,没哟必要显式的实现comparator接口并创建其实例。

2)实例方法引用

这种语法与用于静态方法的语法类似,只不过这里使用对象引用而不是类名。

实例方法引用又分以下三种类型

a.实例上的实例方法引用

组成语法格式:instancereference::methodname

note:

对于具体(或者任意)对象的实例方法引用,在实例方法名称和其所属类型名称间加上分隔符 :

与引用静态方法引用相比,都换为实例对象的而已。

eg:

-- function<string, string> upper = string::touppercase;

--

/*
* 函数式接口
* */
interface stringfunc {
 string func(string n);
}
class mystringops {
 //普通方法: 反转字符串
 public string strreverse(string str) {
 string result = "";
 for (int i = str.length() - 1; i >= 0; i--) {
  result += str.charat(i);
 }
 return result;
 }
}
class methodrefdemo2 {
 public static string stringop(stringfunc sf, string s) {
 return sf.func(s);
 }
 public static void main(string[] args) {
 string instr = "lambda add power to java";
 mystringops strops = new mystringops();//实例对象
 //mystringops::strreverse 相当于实现了接口方法func() ,并在接口方法func()中作了mystringops.strreverse()操作
 string outstr = stringop(strops::strreverse, instr);
 
 system.out.println("original string: " + instr);
 system.out.println("string reserved: " + outstr);
 }
}

输出结果:

original string: lambda add power to java
string reserved: avaj ot rewop dda adbmal

分析:

这里使用了类的名称,而不是具体的对象,尽管指定的是实例方法。使用这种形式时,函数式接口的第一个参数匹配调用对象,第二个参数匹配方法指定的参数。

-- 定义了一个方法counter(),用于统计某个数组中,满足函数式接口myfunc的fun()方法定义的条件的对象个数。本例中,统计hightemp类的实例个数。

interface myfunc<t> {
 boolean func(t v1, t v2);
}
class hightemp {
 private int htemp;
 hightemp(int ht) {
 htemp = ht;
 }
 public boolean sametemp(hightemp ht2) {
 return htemp == ht2.htemp;
 }
 public boolean lessthantemp(hightemp ht2) {
 return htemp < ht2.htemp;
 }
}
class instancemethwithobjectrefdemo {
 public static <t> int counter(t[] vals, myfunc<t> f, t v) {
 int count = 0;
 
 for (int i = 0; i < vals.length; i++) {
  if (f.func(vals[i], v)) count++;
 }
 return count;
 }
 public static void main(string[] args) {
 int count;
 hightemp[] weekdayhighs = {
  new hightemp(89), new hightemp(82),
  new hightemp(90), new hightemp(89),
  new hightemp(89), new hightemp(91),
  new hightemp(84), new hightemp(83)};
 //hightemp::sametemp 为实例方法引用
 count = counter(weekdayhighs, hightemp::sametemp, new hightemp(89));
 system.out.println(count + " days had a high of 89");
 hightemp[] weekdayhighs2 = {
  new hightemp(31), new hightemp(12),
  new hightemp(24), new hightemp(19),
  new hightemp(18), new hightemp(12),
  new hightemp(-1), new hightemp(13)};
 
 count = counter(weekdayhighs2, hightemp::sametemp, new hightemp(12));
 system.out.println(count + " days had a high of 12");
 
 count = counter(weekdayhighs, hightemp::lessthantemp, new hightemp(89));
 system.out.println(count + " days had a high less than 89");
 
 count = counter(weekdayhighs2, hightemp::lessthantemp, new hightemp(19));
 system.out.println(count + " days had a high of less than 19");
 }
}

输出结果:

3 days had a high of 89
2 days had a high of 12
3 days had a high less than 89
5 days had a hign less than 19

分析:

注意hightemp有两个实例方法:sometemp()和lessthantemp()。如果两个hightemp对象包含相同的温度,

sametemp()方法返回true。如果调用对象的温度小于被传递的对象的温度,lessthantemp()方法返回true。这两个方法都有一个hightemp类型的参数,并且都返回布尔结果。因此,这两个方法都与myfunc函数式接口兼容,因为调用对象类型可以映射到func()的第一个参数,传递的实参可以映射到func()的第二个参数。因此,这个表达式:hightemp::sametemp

被传递给counter()方法时,会创建函数式接口的一个实例,其中第一个参数的参数类型就是实例方法的调用对象的类型,也就是hightemp。第二个参数的类型也是hightemp,因为这是sametemp()方法的参数。对于lessthantemp(),这也是成立的。

note:

上面程序中函数式接口中的函数boolean func(t v1,t v2)中含有两个参数,而hightemp中函数sametemp(hightemp ht2)含有一个参数,但是能够兼容的原因是:

其实hightemp类中的sametemp(hightemp ht2)其实包含两个参数,默认隐藏调用这个函数的引用this。

故,当使用类的实例方法作为方法引用时,函数式接口的第一个参数匹配类的实例方法的调用对象,第二个参数才匹配方法指定的参数。

b.超类上的实例方法引用

组成语法格式:super::methodname

方法的名称由methodname指定

通过使用super,可以引用方法的超类版本。

eg: super::name

note:还可以捕获this 指针

this :: equals  等价于lambda表达式  x -> this.equals(x);

c.类型上的实例方法引用
组成语法格式:classname::methodname

note:

若类型的实例方法是泛型的,就需要在::分隔符前提供类型参数,或者(多数情况下)利用目标类型推导出其类型。

静态方法引用和类型上的实例方法引用拥有一样的语法。编译器会根据实际情况做出决定。

一般我们不需要指定方法引用中的参数类型 ,因为编译器往往可以推导出结果,但如果需要我们也可以显式在::分隔符之前提供参数类型信息。

eg:

string::tostring 等价于lambda表达式 (s) -> s.tostring()

这里不太容易理解,实例方法要通过对象来调用,方法引用对应lambda,lambda的第一个参数会成为调用实例方法的对象。

在泛型类或泛型方法中,也可以使用方法引用。

interface myfunc<t> {
 int func(t[] als, t v);
}
class myarrayops {
 public static <t> int countmatching(t[] vals, t v) {
 int count = 0;
 for (int i = 0; i < vals.length; i++) {
  if (vals[i] == v) count++;
 }
 return count;
 }
}
class genericmethodrefdemo {
 public static <t> int myop(myfunc<t> f, t[] vals, t v) {
 return f.func(vals, v);
 }
 public static void main(string[] args){
 integer[] vals = {1, 2, 3, 4, 2, 3, 4, 4, 5};
 string[] strs = {"one", "two", "three", "two"};
 int count;
 count=myop(myarrayops::<integer>countmatching, vals, 4);
 system.out.println("vals contains "+count+" 4s");
 count=myop(myarrayops::<string>countmatching, strs, "two");
 system.out.println("strs contains "+count+" twos");
 }
}

输出结果:

vals contains 3 4s
strs contains 2 twos

分析:

在程序中,myarrayops是非泛型类,包含泛型方法countmatching()。该方法返回数组中与指定值匹配的元素的个数。注意这里如何指定泛型类型参数。例如,在main()方法中,对countmatching()方法的第一次调用如下所示:count = myop(myarrayops::<integer>countmatching,vals,4);
这里传递了类型参数integer。

注意,参数传递发生在::的后面。这种语法可以推广。当把泛型方法指定为方法引用时,类型参数出现在::之后、方法名之前。但是,需要指出的是,在这种情况(和其它许多情况)下,并非必须显示指定类型参数,因为类型参数会被自动推断得出。对于指定泛型类的情况,类型参数位于类名的后面::的前面。

3)构造方法引用

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

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

组成语法格式:class::new

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

eg:

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

--

list<string> strings = new arraylist<string>();
strings.add("a");
strings.add("b");
stream<button> stream = strings.stream().map(button::new);
list<button> buttons = stream.collect(collectors.tolist());

-- 可以把这个引用赋值给定义的方法与构造函数兼容的任何函数式接口的引用

interface myfunc {
 myclass func(int n);
}
class myclass {
 private int val;
 myclass(int v) {
  val = v;
 }
 myclass() {
  val = 0;
 }
 public int getvalue() {
  return val;
 }
}
class constructorrefdemo {
 public static void main(string[] args) {
  myfunc myclasscons = myclass::new;
  myclass mc = myclasscons.func(100);
  system.out.println("val in mc is: " + mc.getvalue());
 }
}

输出结果:

val in mc is: 100

b.数组构造方法引用:

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

eg:

-- int[]::new 是一个含有一个参数的构造器引用,这个参数就是数组的长度。

等价于lambda表达式  x -> new int[x]。

-- 假想存在一个接收int参数的数组构造方法

intfunction<int[]> arraymaker = int[]::new;
int[] array = arraymaker.apply(10) // 创建数组 int[10]

到此这篇关于java8新特性:lambda表达式之方法引用详解的文章就介绍到这了,更多相关java8 lambda表达式之方法引用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!