java的lambda運算式用法

來源:互聯網
上載者:User
lambda運算式的用法 lambda的三個組成部分 一個括弧內用逗號分隔的形式參數,參數是函數式介面裡面方法的參數
IOperation operation = (param) -> ADD_NUM + param;
一個箭頭符號:->
Collections.sort(arrayList,(s1,s2) -> s1.getAge() >= s2.getAge() ? -1 : 1);
方法體,可以是運算式和代碼塊
Thread thread = new Thread(()->{            System.out.println("lambda無參 :" + Thread.currentThread().getName());        });
lambda的介面定義 @FunctionalInterface註解

函數時運算式介面只支援一個抽象方法。

聲明函數式的註解,在編譯時間期檢測介面的寫法。(我用idea編譯器,不寫這個註解也行) 介面定義樣本 介面中支援defualt方法 介面中支援static的實現方法 介面中的toString、hashCode、equals不能被重載

public interface IOperation {    /**     * 加法計算     * @param a     * @return     */    int addOperation(int a);    default int getCount(){        return 1;    }    boolean equals(Object o);    static String getVersion(){        return "1.1";    }}
java.util.function支援的lambda運算式

java.util.function包中提供了很多函數式支援的對象,
有時我們可以使用這寫對象來代替函數式介面 Predicate T作為參數,返回boolean類型,作為一個複雜判斷邏輯的函數式介面對象。

//過濾集合中的男性        List<Person> resList = Lists.newArrayList();        for (int i =0;i<10;i++){            boolean flag = i % 2 == 0;            resList.add(new LambdaClient().new Person("name_"+i,20+i,flag));        }        //1. Predicate 函數式介面的具體實現邏輯        Predicate<Person> isManPredicate = (Person person) -> person.isSex();        List<Person> manList = Lists.newArrayList();        resList.forEach(person -> {            if (isManPredicate.test(person)){                manList.add(person);            }        });        System.out.println("male is " + manList);
Function
//2. Function        Function<Integer, String> f2 = (t)->String.valueOf(t);        String s = f2.apply(2);        System.out.println("Function apply result " + s);
Consumer T作為參數,不返回結果。
 //3. Consumer        Consumer<Person> personConsumer = (Person p) -> {            System.out.println("my name is " + p.getName() + " age is " + p.getAge()                    + " sex is " + (p.isSex() ? "男" : "女"));        };        personConsumer.accept(resList.get(4));
集合的stream(流)式操作 集合StreamCompute方式分為串列流(sequential)和並行流(parallel)
public static List<Integer> getIntegerList(){        List<Integer> list = Lists.newArrayList();        for (int i=1;i<=10000000;i++){            Integer count = new Random().nextInt(i);            list.add(count);        }        return list;    }    /**     * 串列流     */    public static void sequentialStreamDemo(){        List<Integer> list = getIntegerList();        //串列排序,並計算時間        long start = System.nanoTime();        long count = ((Stream)list.stream().sequential()).sorted().count();        long end = System.nanoTime();        long useTime = TimeUnit.NANOSECONDS.toMillis(end - start);        System.out.println("sequential sort count : use time is ms" + useTime);    }    /**     * 並行流     */    public static void parallelStreamDemo(){        List<Integer> list = getIntegerList();        //串列排序,並計算時間        long start = System.nanoTime();        long count = ((Stream)list.stream().parallel()).sorted().count();        long end = System.nanoTime();        long useTime = TimeUnit.NANOSECONDS.toMillis(end - start);        System.out.println("parallell sort count : use time is ms" + useTime);    }
集合StreamCompute過程分為中間操作和終止操作 中間操作返回的對象還是stream,例如filter,sorted,map,group等

返回非stream對象,例如foreach(),sum(),toArray()等

public static void streamListDemo(){    List<LambdaClient.Person> personList = Lists.newArrayList();    for (int i=0;i<50;i++){        personList.add(new LambdaClient.Person("name_"+i,15+i));    }    //過濾30歲以上的person    /**     * filter 傳入的參數是Predicate<T>函數式。     * forEachOrdered 傳入的參數是Consumer<T> 函數式     */    personList.stream().filter(person -> person.getAge()>30).forEachOrdered(            person -> System.out.println("person age 30+ " + person)    );}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.