Java8中Lamda表达式和方法引用的基本语法

Lamda表达式基本实现:

package cn.demo;

@FunctionalInterface//函数式编程注解,只接口允许有一个普通的抽象方法,但可以有 默认方法静态方法
interface IMessage0{
	String msg="xx";
	public static void read() {
	}
	public void print();
	default void write(){
		System.out.println(this.msg);
	}
}
class Action {
	public Action(IMessage0 im){
		im.print();
	}
	public void print(IMessage0 im){
		im.print();
	}
}
public class LamdaTest {

	public static void main(String[] args) {
		IMessage0 im = ()->System.out.println("read");//实例化函数式接口
		im.print();
		
		new Action(()->System.out.println("fuck!"));//传入函数式接口的参数,输出了fuck!
	}

}


方法实现(基于函数式编程的基础上,否则无效):

引用类的方法:类名称::方法名称

引用某个对象的方法:对象名::普通方法

引用构造方法:类名称::new

package cn.demo;

@FunctionalInterface//函数式编程注解,只接口允许有一个普通的抽象方法
interface IUtil<R,P>{
	public R convert(P p,P r);
}
@FunctionalInterface
interface IUtil2<P>{
	public P convert();
}
class Person0 {
	private String name;
	private int age;
	public Person0(String name,int age){
		this.name=name;
		this.age=age;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	
}
@FunctionalInterface
interface IPerson<R,FP,SP> {
	public R create(FP p1,SP p2);
}
public class LamdaTest2 {

	public static void main(String[] args) {
//		IUtil<Integer,String> iu = String :: valueOf;调用静态方法,方法参数被下面改会出错所以注释掉
//		String str = iu.convert(1000);//这里的convert(1000)相当于相当于String.valueOf(1000)
//		System.out.println(str);
		
		IUtil<Integer,String> iu2 = String ::compareTo;//调用普通方法
		System.out.println(iu2.convert("H", "h"));//iu2.convert("H", "h")等同于compareTo("H","h")结果-32
		
		IUtil2<String> iu3 = "hello"::toUpperCase;//调用某个对象的方法
		 System.out.println(iu3.convert());//结果为HELLO
		 
		IPerson<Person0,String,Integer> ip = Person0::new; 
		System.out.println(ip.create("张三", 20));//这里直接返回一个实例化对象,输出Person的toString方法
		 
	}
	

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值