JKD8的新特性——方法引用

方法引用可以看做lambda表达式的深层次的表达,换言之,方法引用就是lambda表达式,也就是函数式接口的一个实例,通过方法的名字指向一个方法。

使用格式:类(对象)::方法名

具体分为如下三种情况:
情况1 对象::非静态方法
情况2 类::静态方法
情况3 类::非静态方法

方法引用使用的要求:要求接口中的抽象方法的形象列表和返回值类型与方法引用的方法的形参列表和返回值类型相同!
例子:
情况一:对象::实例方法

12345678910111213
@Test public void test(){ //情况一:对象::实例方法 //Consumer中的 void accept(T t) //PrintStream中的void println(T t) //lambda表达式 Consumer<String> con=str-> System.out.println(str); con.accept("北京"); System.out.println("_________________________________"); //方法引用 PrintStream printStream = System.out; Consumer<String> con2=printStream::println; }
1234567891011
@Test public void test2(){ //lambda表达式 Employee employee=new Employee(1,"李",21,6000d); Supplier<String> sup=()->employee.getName(); System.out.println(sup.get()); System.out.println("_________________________________"); //方法引用 Supplier<String> sup2=employee::getName; System.out.println(sup2.get()); }

情况二:类::静态方法
Comparator中的int compare(T t1,T t2)
Integer中的int compare(T t1,T t2)
两个方法和参数类型都一致

123456789
@Test public void test3(){ //lambda表达式 Comparator<Integer> com=(t1,t2)->Integer.compare(t1,t2); System.out.println(com.compare(2,3)); //方法引用 Comparator<Integer> com2=Integer::compare; System.out.println(com.compare(5,6));
123456789101112131415
//Function中的R apply(T t) //Math中的Long round(Double d) public void test4(){ //传统的写法 Function<Double,Long> longFunction=new Function<Double, Long>() { @Override public Long apply(Double aDouble) { return Math.round(aDouble); } }; //lambda表达式 Function<Double,Long>function=d->Math.round(d); //方法引用 Function<Double,Long>function1=Math::round; }

情况三:类::实例方法(有难度)
//Comparator中的int compare(T t1,T t2)
//Integer中的int t1.compareTo(t2)

12345678910
@Test public void test5(){ //Lambda表达式 Comparator<Integer>comparator=(s1,s2)->s1.compareTo(s2); System.out.println(comparator.compare(2,3)); System.out.println("_____________________________________"); //方法引用 Comparator<Integer>com=Integer::compare; System.out.println(com.compare(4,3)); }
12345678910111213
//BiPredicate中boolean test(T t1,T t2); //String中的boolean t1.equals(t2) @Test public void test6(){ //lambda表达式 BiPredicate<String,String> biPredicate=(s1,s2)->s1.equals(s2); System.out.println(biPredicate.test("abc","dfg")); System.out.println("_____________________________________"); //方法引用 BiPredicate<String,String> biPredicate2=String::equals; System.out.println(biPredicate2.test("abc","dfg")); }
1234567891011121314
//Function中的R apply(T t) //Employee中的String getName() @Test public void test7(){ Employee employee=new Employee(1,"匈牙利老哥",31,3000); //lambda Function<Employee,String> function=e-> e.getName(); System.out.println(function.apply(employee)); System.out.println("_____________________________________"); //方法引用 //类调用方法 Function<Employee,String>function2=Employee::getName; }
JKD8的新特性——构造器引用及数组引用
JKD8的新特性——lambda的使用条件:函数式接口
评论
zhangrenxian123小白菜
文章28
分类5
标签2