码迷,mamicode.com
首页 > 其他好文 > 详细

Lambda表达式的应用

时间:2019-05-01 11:45:54      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:interface   lint   case   system   and   new   com   trim   name   

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);
    }

Lambda表达式的应用

标签:interface   lint   case   system   and   new   com   trim   name   

原文地址:https://blog.51cto.com/pengge666/2388103

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!