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);
    	}
    
  • 相关阅读:
    hdu-2814-Interesting Fibonacci-斐波那契周期节
    servletContext
    Java中的NIO和IO的对比分析
    sessionID和cookie
    会话跟踪session cookie
    C++中的头文件和源文件
    C++ 头文件
    二叉线索树
    C 二叉树 1
    C 二叉树
  • 原文地址:https://www.cnblogs.com/junzifeng/p/12746037.html
Copyright © 2011-2022 走看看