Lambda表达式的应用

Lambda表达式的应用

调用Collection.sort()方法,通过定制排序比较两个Employee(先按年龄比,年龄相同按姓名比),使用Lambda作为参数传递
List employees = Arrays.asList(
            new Employee("张三", 18 ,9999.99),
            new Employee("李四", 50, 5555.99),
            new Employee("王五", 50, 6666.66),
            new Employee("赵六", 16, 3333.33),
            new Employee("田七", 8, 7777.77)
    );

    @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 employee : employees){
            System.out.println(employee);
        }
    }
1. 声明函数式接口,接口中声明抽象方法,public String getValue(String str);
2. 声明类TestLambda,类中编写方法使用接口作为参数,将一个字符串转换为大写,并作为方法的返回值
3. 再将一个字符串的第2个和第4个索引位置进行截取子串
@FunctionalInterface
public interface MyFunction {

    public String getValue(String str);
}
List employees = Arrays.asList(
            new Employee("张三", 18 ,9999.99),
            new Employee("李四", 50, 5555.99),
            new Employee("王五", 50, 6666.66),
            new Employee("赵六", 16, 3333.33),
            new Employee("田七", 8, 7777.77)
    );

    //需求:用于处理字符串
    public String strHandler(String str, MyFunction mf){
        return mf.getValue(str);
    }

    @Test
    public void test2(){
        String trimStr = strHandler("abfdfdf", (str) -> str.toUpperCase());
        System.out.println(trimStr);

        String subStr = strHandler("abfdfdf", (str) -> str.substring(2, 4));
        System.out.println(subStr);

    }
1. 声明一个带两个泛型的函数式接口,泛型类型为 T为参数,R为返回值
2. 接口中声明对应抽象方法
3. 使用接口作为参数,计算两个long类型参数的和
4. 再计算两个long型参数的乘积
public interface MyFunction2 {

    public R getValue(T t1, T t2);
}
//需求:对于两个Long型数据进行处理
    public void op(Long l1, Long l2, MyFunction2 mf){
        System.out.println(mf.getValue(l1, l2));
    }

    @Test
    public void test3(){
        op(100L, 200L, (x, y) -> x + y);

        op(100L, 200L, (x, y) -> x * y);
    }

当前题目:Lambda表达式的应用
转载来于:http://bzwzjz.com/article/jciicp.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 企业网站建设 成都网站建设 成都响应式网站建设公司 达州网站设计 成都网站设计 重庆电商网站建设 成都网站建设 响应式网站设计 外贸营销网站建设 响应式网站建设 宜宾网站设计 营销网站建设 高端网站建设 成都定制网站建设 成都网站建设流程 成都网站设计公司 成都h5网站建设 成都网站设计 网站设计制作报价 外贸网站建设 企业网站设计 成都网站建设