Java Jdk1.8 Lambda新特性

import java.util.Arrays;
import java.util.Comparator;

/**
	 * 好处1.让代码简介
	 * 2.不会单独生成class文件
	 * 缺点:只有一个抽象方法
	 */
public class LambdaDemo {

	public static void main(String[] args) {
	IEat ieat=new IEatImpl();
	ieat.eat();
	IEat ieat2=new IEatImpl(){
		public void eat(){
			System.out.println("eat bnana");
		}
	};
	ieat2.eat();
	
	Student[] students={
			new Student("张三",18),
			new Student("张四",18),
			new Student("张一",18)};
	//Comparator<Student> c=(o1,o2)->o1.getAge()-o2.getAge();
	//Arrays.sort(students,c);
	Arrays.sort(students,(o1,o2)->o1.getAge()-o2.getAge());
	System.out.println(Arrays.toString(students));
	//lambda写法好处
	/**
	 * 好处1.让代码简介
	 * 2.不会单独生成class文件
	 * 只有一句可以省略{}
	 * 缺点只有一个抽象方法
	 * 
	 */
	IEat ieat3=()->{System.out.println("eat apple");};
	ieat3.eat();
	//没有参数时使用
	IEat ieat4=()->System.out.println("eat 葡萄");
	ieat4.eat();
	//带参数时,参数的类型可以省略
	Play a=(thing,how)->{
		System.out.println("我爱玩"+thing+"用"+how);
		System.out.println(how);
	};
	a.play("LOL","电脑");
	}
	
	//带返回值的
}
//只有一个抽象方法
interface IEat{
	public void eat();
}
interface Play{
	public void play(String thing,String how);
}
interface run{
	public int  howlong();
}
class IEatImpl implements IEat{

	@Override
	public void eat() {
		System.out.println("我吃苹果");		
	}
}
class PlayImpl implements Play{

	@Override
	public void play(String thing,String how) {
		System.out.println("我爱玩"+thing+"用"+how);	
		
	}
	
}


猜你喜欢

转载自blog.csdn.net/weixin_44117272/article/details/89527837