温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Lambda表达式的应用

发布时间:2020-04-03 08:36:14 来源:网络 阅读:432 作者:孤魂1996 栏目:编程语言

Lambda表达式的应用

调用Collection.sort()方法,通过定制排序比较两个Employee(先按年龄比,年龄相同按姓名比),使用Lambda作为参数传递
List<Employee> 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<Employee> 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> T为参数,R为返回值
2. 接口中声明对应抽象方法
3. 使用接口作为参数,计算两个long类型参数的和
4. 再计算两个long型参数的乘积
public interface MyFunction2<T, R> {

    public R getValue(T t1, T t2);
}
//需求:对于两个Long型数据进行处理
    public void op(Long l1, Long l2, MyFunction2<Long, Long> 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);
    }
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI