@Test public void test1(){ //1.对象实例(new出来的)::实例方法名 PrintStream ps=System.out; ps.print("hello"); //Lambda表达式 依赖于函数式接口 Consumer<String> con=(str) -> ps.println(str); con.accept("好久不见"); //方法引用 //1.对象实例::方法实例名 Consumer<String> con1=ps::println; Consumer<String> con2=System.out::println; con1.accept("无风不起浪"); } //2.类名::静态方法名 @Test public void test2(){ BiFunction<Integer,Integer,Integer> bf=(x,y) ->Math.min(x,y); System.out.println("最小值为:"+bf.apply(10,20)); //Lambda表达式 BiFunction<Integer,Integer,Integer> bf1=Math::min; System.out.println("最小值为:"+bf1.apply(1,2)); } //3.类名::实例方法名 @Test public void test3(){ //1.Lambda BiPredicate<String,String> bp=(str1,str2) ->str1.equals(str2); System.out.println(bp.test("hello","hello")); //2.方法的引用:有两个参数的情况 BiPredicate<String,String> bp1=String::equals; System.out.println(bp1.test("duibuqi","hello")); //2.1方法的引用:只有一个参数 Function<TestLambda,String> fun=TestLambda::sayHi; System.out.println(fun.apply(new TestLambda())); } public String sayHi(){ System.out.println("自定义方法"); return "hi"; } //构造器引用 @Test public void test4(){ //调用无参构造方法,获取一个实例 employee emp=new employee(); //Lambda Supplier<employee> sup=() -> new employee();//new employee():无参 System.out.println(sup.get()); //构造器引用 //匹配 无参构造方法 Supplier<employee> sup1=employee::new;//Supplier:无参 System.out.println(sup.get()); //有参数时,匹配带一个字符串的构造方法,并返回 Function<String,employee> fun=employee::new; System.out.println(fun.apply("admin")); } //数组引用 @Test public void test5(){ int[] nums=new int[10]; //Lambda // Function<Integer,Integer[]> fun=(x) ->new Integer[x]; Function<Integer,int[]> fun=(x) ->new int[x]; System.out.println(fun.apply(5).length); //数组引用 Function<Integer,int[]> fun1=int[]::new; int[] num=fun1.apply(10); System.out.println("数组的长度为:"+num.length); }
方法引用,构造器引用,数组引用
最新推荐文章于 2024-09-25 11:06:23 发布