zoukankan      html  css  js  c++  java
  • Java8_方法引用和构造器引用

    方法引用

    当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!(实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!)

    方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。如下三种主要使用情况:
    对象::实例方法
    类::静态方法
    类::实例方法

    例如:

    (x)->System.out.println(x);
    
    等同于:
    
    System.out::println
    

    例如:

    Binaryoperator<Double>bo=(x,y)->Math.pow(x,y);
    
    等同于:
    
    Binaryoperator<Double>bo =Math::pow;
    

    对象的引用 :: 实例方法名

            @Test
    	public void test2(){
    		Employee emp = new Employee(101, "张三", 18, 9999.99);
    		
    		Supplier<String> sup = () -> emp.getName();
    		System.out.println(sup.get());
    		
    		System.out.println("----------------------------------");
    		
    		Supplier<String> sup2 = emp::getName;
    		System.out.println(sup2.get());
    	}	
    

    构造器引用

    格式:ClassName::new
    与函数式接口相结合,自动与函数式接口中方法兼容。可以把构造器引用赋值给定义的方法,与构造器参数列表要与接口中抽象方法的参数列表一致!
    例如:

    Function<Integer,MyClass> fun=(n)->new MyClass(n);
    
    等同于:
    
    Function<Integer,MyClass> fun =lMyclass::new;
    

    //构造器引用

            @Test
    	public void test6(){
    		Supplier<Employee> sup = () -> new Employee();
    		System.out.println(sup.get());
    		
    		System.out.println("------------------------------------");
    		
    		Supplier<Employee> sup2 = Employee::new;
    		System.out.println(sup2.get());
    	}
    

    数组引用

    格式:type]::new
    例如:

    Function<Integer,Integer[]>fun=(n)->new Integer[n];
    
    等同于:
    
    Function<Integer,Integer[]>fun =Integer[]::new;
    

    //数组引用

    	@Test
    	public void test8(){
    		Function<Integer, String[]> fun = (args) -> new String[args];
    		String[] strs = fun.apply(10);
    		System.out.println(strs.length);
    		
    		System.out.println("--------------------------");
    		
    		Function<Integer, Employee[]> fun2 = Employee[] :: new;
    		Employee[] emps = fun2.apply(20);
    		System.out.println(emps.length);
    	}
    
  • 相关阅读:
    pikachu-xss(1)
    eNSP上配置RIPv2的认证
    eNSP模拟器OSPF单区域配置
    OSPF与ACL综合实验
    利用单臂路由实现vlan间路由
    理解Hybrid接口的应用
    eNSP下配置Trunk接口实现跨交换机传递数据
    eNSP上VLAN的基础的配置及access接口
    eNSP下利用三层交换机实现VLAN间路由
    NFS网络文件系统
  • 原文地址:https://www.cnblogs.com/junzifeng/p/12746037.html
Copyright © 2011-2022 走看看