Lambda表達(dá)式的應(yīng)用

Lambda表達(dá)式的應(yīng)用

調(diào)用Collection.sort()方法,通過定制排序比較兩個Employee(先按年齡比,年齡相同按姓名比),使用Lambda作為參數(shù)傳遞
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. 聲明函數(shù)式接口,接口中聲明抽象方法,public String getValue(String str);
2. 聲明類TestLambda,類中編寫方法使用接口作為參數(shù),將一個字符串轉(zhuǎn)換為大寫,并作為方法的返回值
3. 再將一個字符串的第2個和第4個索引位置進(jìn)行截取子串
@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. 聲明一個帶兩個泛型的函數(shù)式接口,泛型類型為<T, R> T為參數(shù),R為返回值
2. 接口中聲明對應(yīng)抽象方法
3. 使用接口作為參數(shù),計(jì)算兩個long類型參數(shù)的和
4. 再計(jì)算兩個long型參數(shù)的乘積
public interface MyFunction2<T, R> {

    public R getValue(T t1, T t2);
}
//需求:對于兩個Long型數(shù)據(jù)進(jìn)行處理
    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);
    }

當(dāng)前標(biāo)題:Lambda表達(dá)式的應(yīng)用
分享URL:http://bm7419.com/article28/jciicp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、軟件開發(fā)、全網(wǎng)營銷推廣App設(shè)計(jì)、網(wǎng)站營銷

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作