Lambda表达式的方法引用与构造器引用Day0817

引用类方法

@FunctionalInterface
interface Fn
{
	double cal(double d1,double d2);
}
public class InvokeStaticMethod 
{
	public static void main(String[] args) 
	{
		// 引用类方法
		Fn fn1 = (d1, d2) -> Math.hypot(d1, d2);
		System.out.println(fn1.cal(3, 4));
		// 本质一样
		Fn fn2 = Math::hypot;
		fn2.cal(3, 4);
	}
}

引用实例方法

@FunctionalInterface
interface Converter
{
	int convert(String str);
}
public class InvokeInstanceMethod
{
	public static void main(String[] args) 
	{
		Converter c1 = str -> str == null ? 0 : str.length();
		System.out.println(c1.convert("InvokeInstanceMethod by lambda"));
		Converter c2 = String::length;
		System.out.println(c2.convert("invoke by ::"));
	}
}

带多个参数的实例方法

@FunctionalInterface
interface Converter
{
	String convert(String str,int start,int end);
}
public class InvokeInstanceMethod1 
{
	public static void main(String[] args) 
	{
		Converter c1 = (str,start,end) -> str.substring(start,end);
		System.out.println(c1.convert("InvokeInstanceMethod by lambda",2,4));
                Converter c2 = String::substring;// 参数1的类型::某个方法
		System.out.println(c2.convert("invoke by ::",2,4));

	}
}

引用特定对象的实例方法

@FunctionalInterface
interface Convert
{
	String convert(int start, int end);
}
public class InvokeConcreteObjInstanceMethod 
{
	public static void main(String[] args) 
	{
		Convert c1 = (start,end) -> "Hello World!".substring(start,end);
		System.out.println(c1.convert(2, 6));
		Convert c2 = "Hello World!"::substring;
		System.out.println(c2.convert(2, 8));
	}
}

构造器引用

import java.util.Date;
@FunctionalInterface
interface Test
{
	Date cal(int a, int b, int c);
}
public class InvokeConstructorByLambda 
{
	public static void main(String[] args) 
	{
		Test t1 = (a, b, c) -> new Date(a, b, c);
		System.out.println(t1.cal(119,7,17));
		Test t2 = Date::new;
		System.out.println(t2.cal(119,7,17));
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值