java8新特性_06_方法引用和构造器引用
2020-08-09 14:38
162 查看
方法引用
一、方法引用:若 Lambda 体内的内容有方法已经实现了, 我们可以使用“方法引用”
(可以理解为方法引用时 Lambda 表达式的另外一种表现形式)
主要有三种语法格式:
对象::实例方法名
类::静态方法名
类::实例方法名
注意:
(1)Lambda 体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数式列表和返回值类型保持一致!
(2)Lambda 参数列表中第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用 ClassName::method
构造器引用
二、构造器引用
格式:ClassName::new
注意:需要调用的构造器的参数列表要与函数式接口中抽象方法参数列表保持一致!
三、数组引用
格式:Type::new
[code]package com.doublew.testJava85; import com.doublew.testJava8.pojo.Employee; import org.junit.Test; import java.io.PrintStream; import java.util.Comparator; import java.util.function.*; public class TestJava85 { //方法引用 //对象::实例方法名 @Test public void test01(){ Consumer con = (x)-> System.out.println(x); PrintStream ps = System.out; Consumer con2 = ps::println; Consumer con3 = System.out::println; con3.accept("wangmeng"); } @Test public void test02(){ Employee e = new Employee(); e.setName("wangmeng"); Supplier s = ()->e.getName(); Supplier s2 = e::getName; System.out.println(s2.get()); Employee e2 = new Employee(); e2.setAge(26); Supplier s3 = e2::getAge; System.out.println(s3.get()); } //方法引用 //类::静态方法 @Test public void test03(){ Comparator<Integer> com = (x,y)->Integer.compare(x,y); Comparator<Integer> com2 = Integer::compare; } //方法引用 //类::实例方法 @Test public void test04(){ BiPredicate<String,String> bp = (x,y)->x.equals(y); BiPredicate<String,String> bp2 = String::equals; } //构造器引用 @Test public void test05(){ Supplier sup = ()->new Employee(); Supplier<Employee> sup2 = Employee::new; Employee e = sup2.get(); System.out.println(e); System.out.println("-------------------------------"); Function<Integer,Employee> fun = (x)->new Employee(x); Function<Integer,Employee> fun2 = Employee::new; System.out.println(fun2.apply(111)); System.out.println("---------------------------------"); BiFunction<Integer,Integer,Employee> bf = Employee::new; System.out.println(bf.apply(123,145)); } //数组引用 //type::new @Test public void test06(){ Function<Integer,String[]> fun = (x)->new String[x]; Function<Integer,String[]> fun2 = String[]::new; System.out.println(fun2.apply(10).length); } }
相关文章推荐
- Java8新特性方法引用、构造器引用、数组引用
- java8新特性总结——lambda表达式之方法引用与构造器引用
- Java8新特性 -- Lambda 方法引用和构造器引用
- java8新特性——方法引用与构造器引用
- java8新特性(方法引用、构造器引用)
- Java8新特性-004-方法、构造器、数组引用
- Java8新特性【方法引用】与【构造器引用】详细讲解
- JAVA8新特性[第三季]-方法引用与构造器引用
- java8新特性——方法引用与构造器引用
- JavaEE进阶知识学习-----Java8新特性知识学习-3-方法引用和构造器引用
- java新特性学习------lambda方法引用、构造器使用、数组引用
- 【Java8新特性】浅谈方法引用和构造器引用
- Java 8新特性-4 方法引用
- Java中Lambda表达式与方法引用和构造器引用
- Java之JDK1.8新特性二(方法引用)
- Java 8新特性:新语法方法引用和Lambda表达式及全新的Stream API
- Java8新特性整理之方法引用(二)
- java8新特性-方法引用
- Java8特性总结(二)Lambda表达式,函数式接口,方法引用
- JAVA8新特性——方法引用