Lamda 学习(一)

小练习:
1、调用Collections.sort()方法,通过定制排序比较两个Employee(先按照年龄比较,年龄相同按照姓名比较)

    @Test
    void test01(){
        List<Employee> emps = Arrays.asList(
                new Employee(27,"刘富贵"),
                new Employee(34,"刘生产"),
                new Employee(23,"刘团结"),
                new Employee(42,"刘向前"),
                new Employee(19,"刘复兴")

        );
        Collections.sort(emps,(e1,e2) -> {
            if(e1.getAge() == e2.getAge()){
                return e1.getName().compareTo(e2.getName());
            }
            return Integer.compare(e1.getAge(),e2.getAge());
        });
        
        for (Employee emp : emps) {
            System.out.println(emp);
        }
    }

2、

  1. 声明一个函数式接口,接口中声明抽象方法,public string getValue(String str)
  2. 声明一个类,类中编写方法使用接口作为参数,将一个字符串转换为大写,并作为方法的返回值
  3. 将一个字符串的第二和第四索引位置进行截取字符串
//函数式接口
@FunctionalInterface
public interface MyFunction {
	//类型是确定的
    public String getValue(String str);
}
	//方法
    public String stringHandler(String str, MyFunction mf){
        return mf.getValue(str);
    }
    @Test
    void test02(){
    	//将字符串转换为大写
        String xiaowu = stringHandler("xiaowu", (str) -> str.toUpperCase());
        //截取字符串
        String subStr = stringHandler("xiaowu", (str) -> str.substring(2, 4));
		
        System.out.println(xiaowu);
        System.out.println(subStr);
    }

3、声明一个接受泛型参数的函数式接口

@FunctionalInterface
public interface MyFunctionGenerictity<T,R> {
    R getValue(T t1,T t2);
}
    //接受两个Long型数据进行处理
    public void operation(Long l1, Long l2, MyFunctionGenerictity<Long,Long> mg){
        System.out.println(mg.getValue(l1,l2));
    }
    @Test
    void test03(){
        //2、声明一个接受泛型参数的函数式接口,
        operation(2L,4L,(x,y) -> x * y);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值