Lambda 表达式的应用

List<Employee> employees = Arrays.asList(
        new Employee("张小", 19, 1999.99),
        new Employee("李而", 18, 2999.99),
        new Employee("张三", 20, 3999.99),
        new Employee("张四", 50, 4999.99),
        new Employee("王五", 38, 5555.55),
        new Employee("赵六", 30, 6666.66),
        new Employee("田七", 21, 7777.77)
);
/**
 * 调用Collection.sort()方法,通过定制排序比较两个Employee(先按年龄,年龄相同按姓名比)。
 * 使用Lambda作为参数传递
 */
@Test
public void test1(){
    Collections.sort(employees,(e1,e2)->{
        if (e1.getAge()==e2.getAge()){
            return e1.getName().compareTo(e2.getName());
        }else {
            return  Integer.compare(e1.getAge(),e2.getAge());
            //return -Integer.compare(e1.getAge(),e2.getAge());
        }
    });

    for (Employee emp: employees) {
        System.out.println(emp);
    }
}
/**
 * 声明函数式接口,接口中声明抽象方法,public String getValue();
 * 声明类TestLambda,类中编写方法使用接口作为参数,将一个字符品转换成大写,并作为方法的返回值
 * 再将一个字符串的第2个和第4个索引位置进行截取子串
 */
@Test
public void test2(){
    String trimStr = strHandler("\t\t\t 我大北大荒威武   ", (str) -> str.trim());
    System.out.println(trimStr);

    String upperStr = strHandler("abcdef", (str) -> str.toUpperCase());
    System.out.println(upperStr);

    String newStr = strHandler("我大北大荒威武", (str) -> str.substring(2, 5));
    System.out.println(newStr);
}
//需求:用于处理字符串
public String strHandler(String str, MyFunction myFunction){
    return myFunction.getValue(str);
}

/**
 * 声明一个带两个泛型的函数式接口,泛型类型为<T,R> T为参数,R为返回值
 * 接口中声明对应抽象方法
 * 在TestLambda类中声明方法,使得接口作为参数,计算两个long型参数的和
 * 再计算两个long型参数的乘积
 */
@Test
public void test3(){
    op(100L,200L,(x,y)->x+y);
    op(100L,200L,(x,y)->x*y);
}
//需求:对于两个Long型数据进行处理
public void op(Long L1, Long L2, MyFunctionLong<Long,Long> mf){
    System.out.println(mf.getValue(L1,L2));
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值