java8新特性_04_Lambda表达式练习

本文通过具体示例介绍了Java8中的Lambda表达式和函数式接口的使用,包括自定义排序、字符串处理及数值运算。通过策略设计模式展示了如何利用函数式接口进行灵活的代码设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class TestJava83 {

    List<Employee> emplpoyees = Arrays.asList(
            new Employee("张四",33,988.88),
            new Employee("张三",23,888.88),
            new Employee("张吴",43,9988.88),
            new Employee("张六",53,8998.88));

    //需求1:调用Collections.sort方法,自定义排序,Employee先按年龄排序,再按名称排序
    @Test
    public void test01(){
        Collections.sort(emplpoyees,(e1,e2)->{
            if(e1.getAge()==e2.getAge()){
                return e1.getName().compareTo(e2.getName());
            }else{
                return Integer.compare(e1.getAge(),e2.getAge());
            }
        });

        emplpoyees.forEach(e->{
            System.out.println(e);
        });
    }


    //需求2:定义函数式接口MyFunInter,接口中定义方法getValue,声明类,类中方法 将接口作为参数,将传入的字符串参数转大写,截取
    @Test
    public void test02(){
        System.out.println(toCast("hello wangmeng", x -> x.toUpperCase()));
        System.out.println(toCast("hellowangmeng", x -> x.substring(2,4)));
    }
    //策略设计模式
    public String toCast(String data, MyfunInter mfi){
        return mfi.getValue(data);
    }


    //需求3:
    @Test
    public void test03(){
        System.out.println(longMethod(2l, 5l, (x, y) -> x + y));
        System.out.println(longMethod(2l, 5l, (x, y) -> x * y));
    }
    //策略设计模式
    public Long longMethod(Long t1,Long t2, MyFunInter2<Long, Long> mfi2){
        return mfi2.myMethod(t1,t2);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值