為什么需要lambda

OOP vs lambda

如果說面向?qū)ο缶幊虝r對數(shù)據(jù)的抽象,那么函數(shù)式編程就是對行為的抽象。lambda 更利于實現(xiàn)并行編程并且更加的簡潔。

lambda 的寫法

->將lambda分為兩個部分:左邊是參數(shù),右邊是語句。
②參數(shù)不需要寫明參數(shù)類型,javac會根據(jù)上下文進(jìn)行類型推斷。
③當(dāng)沒有參數(shù)時,左邊為()就行
④當(dāng)只有一行語句時{}可以省略

1.  Runnable noArguments = () -> System.out.println("Hello World");
2.ActionListener oneArgument = event -> System.out.println("button clicked");
3.Runnable multiStatement = () -> {
System.out.print("Hello");
System.out.println(" World");
};
4.BinaryOperator<Long> add = (x, y) -> x + y;
5.BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;

函數(shù)式接口

只有一個抽象方法的接口稱之為函數(shù)式接口。lambda可以很簡潔的實現(xiàn)函數(shù)式接口。java8自帶了一些函數(shù)式接口

函數(shù) 參數(shù) 返回值 example
Predicate<T> T boolean Has this album been released yet?
Consumer<T> T void Printing out a value
Function<T,R> T R Get the name from an Artist obj
Supplier<T> None T A factory method
UnaryOperator<T> T T Logical not (!)
BinaryOperator<T> (T, T) T Multiplying two numbers (*)

Stream

Stream是支持順序和并行聚合操作的元素序列,并且函數(shù)操作基于lambda編程范式實現(xiàn)
java 官網(wǎng)關(guān)于Strem特征的介紹

Stream 上的操作為管道操作,它由如下要素構(gòu)成

  • 數(shù)據(jù)源,比如集合,數(shù)組,IO channel 構(gòu)成
  • 中間操作,比如filter 過濾操作,distinct去重操作
  • 終止操作,比如 count() or forEach(Consumer))
    流是惰性執(zhí)行的,僅在啟動終止操作時才對源數(shù)據(jù)執(zhí)行管道計算
操作類型 接口方法
中間操作 concat() distinct() empty() filter() flatMap() flatMapToDouble() flatMapToInt() flatMapToLong() generate() iterate() limit() map() mapToDouble() mapToInt() mapToLong() of() peek() skip() sorted() parallel() sequential() unordered()
終止操作 allMatch() anyMatch() collect() count() findAny() findFirst() forEach() forEachOrdered() max() min() noneMatch() reduce() toArray()

集合類轉(zhuǎn)Stream

java中的集合類可以方便的轉(zhuǎn)化為Stream 然后應(yīng)用lambda

Collection 類簽名

public interface Collection<E> extends Iterable<E> 

Collection 中提供了兩個轉(zhuǎn)化為Stream的方法

  • stream()
  • parallelStream()

list,set,queue因為實現(xiàn)的Collection 接口所以可以直接調(diào)用stream()parallelStream()轉(zhuǎn)為Stream
map 沒有實現(xiàn)Collection接口,但是map可以調(diào)用 map.entrySet(), map.keySet(),map.values()轉(zhuǎn)為集合類然后使用Stream方法

java集合類圖

小demo

map格式化為String,以及String 轉(zhuǎn)map

      Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        String mapString=map.keySet().stream().map(k -> k + "=" + map.get(k)).collect(Collectors.joining(",", "{", "}"));
        System.out.println(mapString);
        Arrays.stream(mapString.split(",")).map(entry->entry.split("=")).collect(Collectors.toMap(e->e[0],e->e[1]));

參考

https://www.cnblogs.com/CarpenterLee/category/965121.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容