**
JDK8 Stream 流
**
概述
繼Java 8系列之Lambda表達式之後,我們來了解Stream。Stream 是用函數式編程方式在集合類上進行復雜操作的工具,其集成了Java 8中的衆多新特性之一的聚合操作,開發者可以更容易地使用Lambda表達式,並且更方便地實現對集合的查找、遍歷、過濾以及常見計算等。
創建Stream
我們有多種方式生成Stream:
- Stream接口的靜態工廠方法(注意:Java8裏接口可以帶靜態方法);
- Collection接口和數組轉換成Stream ;
- 通過Stream.of(T) 靜態方法創建流;
Stream API 使用:
filter
filter方法對原Stream按照指定條件過濾,在新建的Stream中,只包含滿足條件的元素,將不滿足條件的元素過濾掉。
ArrayList<String> list = new ArrayList<String>();
list.add("A1");
list.add("A2");
list.add("A3");
list.add("A4");
list.add("A5");
Stream<String> stream = list.stream(); //collection 轉 stream
list.stream().filter((str)->str != "A4").forEach((str)->System.out.println(str));
forEach
forEach方法前面已經用了好多次,其用於遍歷Stream中的所元素,避免了使用for循環,讓代碼更簡潔,邏輯更清晰。
Stream.of("1","2").forEach((str)->System.out.println(str));
map
map方法將對於Stream中包含的元素使用給定的轉換函數進行轉換操作,新生成的Stream只包含轉換生成的元素。爲了提高處理效率,官方已封裝好了,三種變形:mapToDouble,mapToInt,mapToLong。其實很好理解,如果想將原Stream中的數據類型,轉換爲double,int或者是long是可以調用相對應的方法。
Stream<String> stream2 = Stream.of("1","2","3");
// map 方法參數 function<T,R> 相當於映射 將T轉爲R類型
Stream<Integer> stream2New = stream2.map((str)->{return Integer.parseInt(str);});
stream2New.forEach((str)->System.out.println(str));
count
count方法將返回Stream中元素的個數。(相當於集合中size)
Stream<String> stream3 = Stream.of("1","2","3");
System.out.println(stream3.count()); //相當於集合中的size 統計元素個數
limit
limit方法將截取原Stream,截取後Stream的最大長度不能超過指定值N。如果原Stream的元素個數大於N,將截取原Stream的前N個元素;如果原Stream的元素個數小於或等於N,將截取原Stream中的所有元素。
Stream<String> stream4 = Stream.of("1","2","3");
stream4.limit(2).forEach((str)->System.out.println(str)); //將stream 中的數據進行截取 返回新的流
skip
skip方法將過濾掉原Stream中的前N個元素,返回剩下的元素所組成的新Stream。如果原Stream的元素個數大於N,將返回原Stream的後(原Stream長度-N)個元素所組成的新Stream;如果原Stream的元素個數小於或等於N,將返回一個空Stream。
Stream<String> stream5 = Stream.of("1","2","3");
stream5.skip(2).forEach((str)->System.out.println(str)); //從stream 中跳過指定索引的流,指定索引大於索引個數將返回空流
concat
concat方法將兩個Stream連接在一起,合成一個Stream。若兩個輸入的Stream都時排序的,則新Stream也是排序的;若輸入的Stream中任何一個是並行的,則新的Stream也是並行的;若關閉新的Stream時,原兩個輸入的Stream都將執行關閉處理
Stream<String> streamA = Stream.of("1","2","3");
Stream<String> streamB = Stream.of("3","2","1");
Stream.concat(streamA, streamB).forEach((str)->System.out.println(str)); //stream 靜態方法 concat 將兩個流合併一起返回新流
持續更新~