0
点赞
收藏
分享

微信扫一扫

springboot打包笔记

互联网码农 2024-06-03 阅读 19

Lambda表达式

简介
基础语法

无参数、无返回值的抽象方法

public class Test1 {
	@Test
	public void test01() {
//		I1 i1 = new I1() {
//			@Override
//			public void method() {
//				System.out.println("传统使用匿名内部类的方式");
//			}
//		};
//		i1.method();

		I1 i1 = ()-> System.out.println("采用Lambda表达式的方式");
		i1.method();
	}
}
interface I1{
	public void method();//无参数、无返回值的抽象方法
}

一个参数、无返回值的抽象方法

public class Test1 {
	@Test
	public void test01() {
		I1 i1 = (x)-> System.out.println("采用Lambda表达式的方式 " + x);
		i1.method(1000);
	}
}
interface I1{
	public void method(int num1);//一个参数、无返回值的抽象方法
}

多个参数、无返回值的抽象方法

public class Test1 {
	@Test
	public void test01() {
		I1 i1 = (x,y,z)-> 
        System.out.println("采用Lambda表达式的方式 " + x + y + z);
        i1.method(1000,2000,3000);
	}
}
interface I1{
    //多个参数、无返回值的抽象方法
	public void method(int num1,int num2,int num3);
}

多个参数、有返回值的抽象方法

public class Test1 {
	@Test
	public void test01() {
		I1 i1 = (x,y,z)-> x+y+z;
		int result = i1.method(1000,2000,3000);
		System.out.println(result);
	}
}
interface I1{
        //多个参数、有返回值的抽象方法
        public int method(int num1,int num2,int num3);
}
注意点
public class Test1 {
	@Test
	public void test01() {
		int x;
		int num = 10;
		I1 i1 = x -> System.out.println(x + (num++));
        i1.method(1000);
		
		I2 i2 = (int x,int y) -> {
			int result = x+y;
			return result;
		};
		int result = i2.method(10, 20);
		System.out.println(result);
	}
}
interface I1{
	public void method(int num1);
}
interface I2{
	public int method(int num1,int num2);
}
练习
public class Test1 {
	@Test
	public void test01() {
		List<Student> stuList = Arrays.asList(
				new Student("张三", 28, 4800,Course.JAVA),new Student("李四", 36, 7200,Course.JAVA),new Student("王五", 19, 9600,Course.HTML),new Student("赵六", 42, 6100,Course.HTML),new Student("孙七", 23, 9600,Course.PYTHON),new Student("吴八", 31, 3000,Course.PYTHON));
		
		Collections.sort(stuList, (a,b)-> {
			if(a.getAge() == b.getAge()){
				return Double.compare(a.getSalary(),b.getSalary());
			}
                return a.getAge()-b.getAge();
		});
		
		for (Student stu : stuList) {
			System.out.println(stu);
		}
	}
}
enum Course{//课程枚举
	JAVA,HTML,PYTHON;
}
class Student{//学生类
	
	private String name;
	private int age;
	private double salary;
	private Course course;
    ...
}
public class Test1 {
	@Test
	public void test01() {
		String strHandler = strHandler("abc", x-> x.toUpperCase());
		System.out.println(strHandler);
	}
	public static String strHandler(String str,I1 i1){
		return i1.getValue(str);
	}
}
interface I1{
	public String getValue(String str);
}
public class Test1 {
	@Test
	public void test01() {
		Long addLong = addLong(100L, 200L, (x,y)-> x+y);
		System.out.println(addLong);
	}
	public static Long addLong(Long l1,Long l2,I1<Long,Long> i1){
		return i1.add(l1, l2);
	}
}
interface I1<T,R>{
	public R add(T t1,T t2);
}

举报

相关推荐

0 条评论