一、什么是Stream
1.Stream 作為 Java 8 的一大亮點雄坪,它與Java.io 包里的InputStream 和 OutputStream是完全不同的概念厘熟。
它也不同于 StAX 對 XML 解析的 Stream,也不是 Amazon Kinesis 對大數(shù)據(jù)實時處理的 Stream维哈。
Java 8 中的 Stream 是對集合(Collection)對象功能的增強绳姨,它專注于對集合對象進行各種非常便利、高效的聚合操作(aggregate operation)阔挠,
或者大批量數(shù)據(jù)操作 (bulk data operation)飘庄。Stream API 借助于同樣新出現(xiàn)的 Lambda 表達式,極大的提高編程效率和程序可讀性购撼。
同時它提供串行和并行兩種模式進行匯聚操作跪削,并發(fā)模式能夠充分利用多核處理器的優(yōu)勢谴仙,使用 fork/join 并行方式來拆分任務(wù)和加速處理過程。
通常編寫并行代碼很難而且容易出錯, 但使用 Stream API 無需編寫一行多線程的代碼碾盐,就可以很方便地寫出高性能的并發(fā)程序晃跺。
所以說,Java 8 中首次出現(xiàn)的 java.util.stream 是一個函數(shù)式語言+多核時代綜合影響的產(chǎn)物毫玖。
二掀虎、Java7和Java8 聚合操作的區(qū)別。
// java 7 中的排序和取值實現(xiàn)
List<Transaction> groceryTransactions = new Arraylist<>();
for(Transaction t: transactions){
if(t.getType() == Transaction.GROCERY){
groceryTransactions.add(t);
}
}
Collections.sort(groceryTransactions, new Comparator(){
public int compare(Transaction t1, Transaction t2){
return t2.getValue().compareTo(t1.getValue());
}
});
List<Integer> transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions){
transactionsIds.add(t.getId());
}
// 而在 Java 8 使用 Stream付枫,代碼更加簡潔易讀烹玉;而且使用并發(fā)模式,程序執(zhí)行速度更快阐滩。
List<Integer> transactionsIds = transactions.parallelStream().
filter(t -> t.getType() == Transaction.GROCERY).
sorted(comparing(Transaction::getValue).reversed()).
map(Transaction::getId).
collect(toList());
三二打、Stream 總覽
Stream 不是集合元素,它不是數(shù)據(jù)結(jié)構(gòu)并不保存數(shù)據(jù)叶眉,它是有關(guān)算法和計算的,它更像一個高級版本的 Iterator芹枷。
原始版本的 Iterator衅疙,用戶只能顯式地一個一個遍歷元素并對其執(zhí)行某些操作;高級版本的 Stream鸳慈,用戶只要給出需要對其包含的元素執(zhí)行什么操作饱溢。
比如 “過濾掉長度大于 10 的字符串”、“獲取每個字符串的首字母”等走芋,Stream 會隱式地在內(nèi)部進行遍歷绩郎,做出相應的數(shù)據(jù)轉(zhuǎn)換。
## Stream 就如同一個迭代器(Iterator)翁逞,單向肋杖,不可往復,數(shù)據(jù)只能遍歷一次挖函,遍歷過一次后即用盡了状植,就好比流水從面前流過,一去不復返怨喘。
## 但是Stream 的另外一大特點是津畸,數(shù)據(jù)源本身可以是無限的。
而和迭代器又不同的是必怜,Stream 可以并行化操作肉拓,迭代器只能命令式地、串行化操作梳庆。顧名思義暖途,當使用串行方式去遍歷時卑惜,每個 item 讀完后再讀下一個 item。
而使用并行去遍歷時丧肴,數(shù)據(jù)會被分成多個段残揉,其中每一個都在不同的線程中處理,然后將結(jié)果一起輸出芋浮。
Stream 的并行操作依賴于 Java7 中引入的 Fork/Join 框架(JSR166y)來拆分任務(wù)和加速處理過程抱环。
// 有多種方式生成 Stream :
從 Collection 和數(shù)組, 用得最多
Collection.stream()
Collection.parallelStream()
Arrays.stream(T array) or Stream.of()
從 BufferedReader
java.io.BufferedReader.lines()
其它
Random.ints()
BitSet.stream()
Pattern.splitAsStream(java.lang.CharSequence)
JarFile.stream()
// 流的操作類型分為兩種:
Intermediate:一個流可以后面跟隨零個或多個 intermediate 操作纸巷。其目的主要是打開流镇草,做出某種程度的數(shù)據(jù)映射/過濾,然后返回一個新的流瘤旨,交給下一個操作使用梯啤。
這類操作都是惰性化的(lazy),就是說存哲,僅僅調(diào)用到這類方法因宇,并沒有真正開始流的遍歷。
Terminal:一個流只能有一個 terminal 操作,當這個操作執(zhí)行后,流就被使用“光”了愉适,無法再被操作敛滋。所以這必定是流的最后一個操作。
Terminal 操作的執(zhí)行,才會真正開始流的遍歷,并且會生成一個結(jié)果,或者一個 (副作用)side effect饲化。
#還有一種操作被稱為 short-circuiting。用以指:
對于一個 intermediate 操作吗伤,如果它接受的是一個無限大(infinite/unbounded)的 Stream吃靠,但返回一個有限的新 Stream。
對于一個 terminal 操作足淆,如果它接受的是一個無限大的 Stream撩笆,但能在有限的時間計算出結(jié)果。
// 一個流操作的示例缸浦。filter 和 mapToInt 為 intermediate 操作夕冲,進行數(shù)據(jù)篩選和轉(zhuǎn)換。
最后一個 sum() 為 terminal 操作裂逐,對符合條件的全部小物件作重量求和歹鱼。
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
四、Stream 的使用詳解
簡單說卜高,對 Stream 的使用就是實現(xiàn)一個 filter-map-reduce 過程弥姻,產(chǎn)生一個最終結(jié)果南片,或者導致一個副作用(side effect)。
下面提供最常見的幾種構(gòu)造 Stream 的樣例庭敦。
構(gòu)造流的幾種常見方法
// 1. Individual values
Stream stream = Stream.of("a", "b", "c");
// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
// 3. Collections
List<String> list = Arrays.asList(strArray);
stream = list.stream();
##需要注意的是疼进,對于基本數(shù)值型,目前有三種對應的包裝類型 Stream:
IntStream秧廉、LongStream伞广、DoubleStream。當然我們也可以用 Stream<Integer>疼电、Stream<Long>嚼锄、Stream<Double>,
但是 boxing 和 unboxing 會很耗時蔽豺,所以特別為這三種基本數(shù)值型提供了對應的 Stream区丑。
Java 8 中還沒有提供其它數(shù)值型 Stream,因為這將導致擴增的內(nèi)容較多修陡。而常規(guī)的數(shù)值型聚合運算可以通過上面三種 Stream 進行沧侥。
// 數(shù)值流的構(gòu)造
IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);
##流轉(zhuǎn)換為其它數(shù)據(jù)結(jié)構(gòu),用得很多
// 1. Array
String[] strArray1 = stream.toArray(String[]::new);
// 2. Collection
List<String> list1 = stream.collect(Collectors.toList());
List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
Set set1 = stream.collect(Collectors.toSet());
Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));
// 3. String
String str = stream.collect(Collectors.joining()).toString();
#PS: 一個 Stream 只可以使用一次魄鸦,上面的代碼為了簡潔而重復使用了數(shù)次宴杀。
流的操作
接下來,當把一個數(shù)據(jù)結(jié)構(gòu)包裝成 Stream 后号杏,就要開始對里面的元素進行各類操作了婴氮。
常見的操作可以歸類如下斯棒。
Intermediate:
map (mapToInt, flatMap 等)盾致、 filter、 distinct荣暮、 sorted庭惜、 peek、 limit穗酥、 skip护赊、 parallel、 sequential砾跃、 unordered
Terminal:
forEach骏啰、 forEachOrdered、 toArray抽高、 reduce判耕、 collect、 min翘骂、 max壁熄、 count帚豪、 anyMatch、 allMatch草丧、 noneMatch狸臣、 findFirst、 findAny昌执、 iterator
Short-circuiting:
anyMatch烛亦、 allMatch、 noneMatch仙蚜、 findFirst此洲、 findAny、 limit
##>> map 和 flatMap <<##
我們先來看 map委粉。如果你熟悉 scala 這類函數(shù)式語言呜师,對這個方法應該很了解。
它的作用就是把 input Stream 的每一個元素贾节,映射成 output Stream 的另外一個元素汁汗。
// 轉(zhuǎn)換大寫
List<String> output = wordList.stream().
map(String::toUpperCase).
collect(Collectors.toList());
// 平方數(shù)
List<Integer> nums = Arrays.asList(1, 2, 3, 4);
List<Integer> squareNums = nums.stream().
map(n -> n * n).
collect(Collectors.toList());
## 從上面例子可以看出,map 生成的是個 1:1 映射栗涂,每個輸入元素知牌,都按照規(guī)則轉(zhuǎn)換成為另外一個元素。
## 還有一些場景斤程,是一對多映射關(guān)系的角寸,這時需要 flatMap。
// 一對多忿墅,flatMap 把 input Stream 中的層級結(jié)構(gòu)扁平化扁藕,就是將最底層元素抽出來放到一起。
// 最終 output 的新 Stream 里面已經(jīng)沒有 List 了疚脐,都是直接的數(shù)字亿柑。
Stream<List<Integer>> inputStream = Stream.of(
Arrays.asList(1),
Arrays.asList(2, 3),
Arrays.asList(4, 5, 6)
);
Stream<Integer> outputStream = inputStream.
flatMap((childList) -> childList.stream());
##>> filter <<##
filter 對原始 Stream 進行某項測試,通過測試的元素被留下來生成一個新 Stream棍弄。
// 留下偶數(shù),經(jīng)過條件“被 2 整除”的 filter望薄,剩下的數(shù)字為 {2, 4, 6}。
Integer[] sixNums = {1, 2, 3, 4, 5, 6};
Integer[] evens =
Stream.of(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);
// 把單詞挑出來呼畸,這段代碼首先把每行的單詞用 flatMap 整理到新的 Stream痕支,
// 然后保留長度不為 0 的,就是整篇文章中的全部單詞了蛮原。
List<String> output = reader.lines().
flatMap(line -> Stream.of(line.split(REGEXP))).
filter(word -> word.length() > 0).
collect(Collectors.toList());
##>> forEach <<##
forEach 方法接收一個 Lambda 表達式卧须,然后在 Stream 的每一個元素上執(zhí)行該表達式。
// 打印姓名(forEach 和 java8之前版本的代碼 的對比)
// Java 8
roster.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.forEach(p -> System.out.println(p.getName()));
// Java 8之前版本
for (Person p : roster) {
if (p.getGender() == Person.Sex.MALE) {
System.out.println(p.getName());
}
}
## 另外一點需要注意,forEach 是 terminal 操作故慈,因此它執(zhí)行后板熊,Stream 的元素就被“消費”掉了。
## 你無法對一個 Stream 進行兩次 terminal 運算察绷。下面的代碼是錯誤的:
stream.forEach(element -> doOneThing(element));
stream.forEach(element -> doAnotherThing(element));
// 同時干签,forEach 不能修改自己包含的本地變量值,也不能用 break/return 之類的關(guān)鍵字提前結(jié)束循環(huán)拆撼。
##>> peek <<##
// 相反容劳,具有相似功能的 intermediate 操作 peek 可以達到上述目的。如下是出現(xiàn)在該 api javadoc 上的一個示例闸度。
// peek 對每個元素執(zhí)行操作并返回一個新的 Stream
Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e))
.collect(Collectors.toList());
##>> findFirst <<##
這是一個 termimal 兼 short-circuiting 操作竭贩,它總是返回 Stream 的第一個元素,或者空莺禁。
這里比較重點的是它的返回值類型:Optional留量。這也是一個模仿 Scala 語言中的概念,作為一個容器哟冬,它可能含有某值楼熄,或者不包含。
使用它的目的是盡可能避免 NullPointerException浩峡。
// Optional 的兩個用例
String strA = " abcd ", strB = null;
print(strA);
print("");
print(strB);
getLength(strA);
getLength("");
getLength(strB);
public static void print(String text) {
// Java 8
Optional.ofNullable(text).ifPresent(System.out::println);
// Pre-Java 8
if (text != null) {
System.out.println(text);
}
}
public static int getLength(String text) {
// Java 8
return Optional.ofNullable(text).map(String::length).orElse(-1);
// Pre-Java 8
// return if (text != null) ? text.length() : -1;
};
在更復雜的 if (xx != null) 的情況中可岂,使用 Optional 代碼的可讀性更好,而且它提供的是編譯時檢查翰灾,
能極大的降低 NPE 這種 Runtime Exception 對程序的影響缕粹,或者迫使程序員更早的在編碼階段處理空值問題,而不是留到運行時再發(fā)現(xiàn)和調(diào)試纸淮。
##>> reduce <<##
這個方法的主要作用是把 Stream 元素組合起來平斩。
它提供一個起始值(種子),然后依照運算規(guī)則(BinaryOperator)萎馅,和前面 Stream 的第一個双戳、第二個虹蒋、第 n 個元素組合糜芳。
從這個意義上說,字符串拼接魄衅、數(shù)值的 sum峭竣、min、max晃虫、average 都是特殊的 reduce皆撩。例如 Stream 的 sum 就相當于
Integer sum = integers.reduce(0, (a, b) -> a+b); 或
Integer sum = integers.reduce(0, Integer::sum);
// 也有沒有起始值的情況,這時會把 Stream 的前面兩個元素組合起來,返回的是 Optional扛吞。
// reduce 的用例
// 字符串連接呻惕,concat = "ABCD"
String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
// 求最小值,minValue = -3.0
double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
// 求和滥比,sumValue = 10, 有起始值
int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
// 求和亚脆,sumValue = 10, 無起始值
sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();
// 過濾,字符串連接盲泛,concat = "ace"
concat = Stream.of("a", "B", "c", "D", "e", "F").
filter(x -> x.compareTo("Z") > 0).
reduce("", String::concat);
上面代碼例如第一個示例的 reduce()濒持,第一個參數(shù)(空白字符)即為起始值,第二個參數(shù)(String::concat)為 BinaryOperator寺滚。
這類有起始值的 reduce() 都返回具體的對象柑营。而對于第四個示例沒有起始值的 reduce(),由于可能沒有足夠的元素村视,返回的是 Optional官套,請留意這個區(qū)別。
##>> limit/skip <<##
limit 返回 Stream 的前面 n 個元素蚁孔;skip 則是扔掉前 n 個元素(它是由一個叫 subStream 的方法改名而來)虏杰。
// limit 和 skip 對運行次數(shù)的影響
public void testLimitAndSkip() {
List<Person> persons = new ArrayList();
for (int i = 1; i <= 10000; i++) {
Person person = new Person(i, "name" + i);
persons.add(person);
}
List<String> personList2 = persons.stream().
map(Person::getName).limit(10).skip(3).collect(Collectors.toList());
System.out.println(personList2);
}
private class Person {
public int no;
private String name;
public Person (int no, String name) {
this.no = no;
this.name = name;
}
public String getName() {
System.out.println(name);
return name;
}
// 輸出結(jié)果為:
name1
name2
name3
name4
name5
name6
name7
name8
name9
name10
[name4, name5, name6, name7, name8, name9, name10]
這是一個有 10,000 個元素的 Stream勒虾,但在 short-circuiting 操作 limit 和 skip 的作用下纺阔,
管道中 map 操作指定的 getName() 方法的執(zhí)行次數(shù)為 limit 所限定的 10 次,而最終返回結(jié)果在跳過前 3 個元素后只有后面 7 個返回修然。
有一種情況是 limit/skip 無法達到 short-circuiting 目的的笛钝,就是把它們放在 Stream 的排序操作后,
原因跟 sorted 這個 intermediate 操作有關(guān):此時系統(tǒng)并不知道 Stream 排序后的次序如何愕宋,
所以 sorted 中的操作看上去就像完全沒有被 limit 或者 skip 一樣玻靡。
// limit 和 skip 對 sorted 后的運行次數(shù)無影響
List<Person> persons = new ArrayList();
for (int i = 1; i <= 5; i++) {
Person person = new Person(i, "name" + i);
persons.add(person);
}
List<Person> personList2 = persons.stream().sorted((p1, p2) ->
p1.getName().compareTo(p2.getName())).limit(2).collect(Collectors.toList());
System.out.println(personList2);
即雖然最后的返回元素數(shù)量是 2,但整個管道中的 sorted 表達式執(zhí)行次數(shù)沒有像前面例子相應減少中贝。
// 最后有一點需要注意的是囤捻,對一個 parallel 的 Steam 管道來說,如果其元素是有序的邻寿,那么 limit 操作的成本會比較大蝎土,
// 因為它的返回對象必須是前 n 個也有一樣次序的元素。取而代之的策略是取消元素間的次序绣否,或者不要用 parallel Stream誊涯。
##>> sorted <<##
對 Stream 的排序通過 sorted 進行,它比數(shù)組的排序更強之處在于:
你可以首先對 Stream 進行各類 map蒜撮、filter暴构、limit、skip 甚至 distinct 來減少元素數(shù)量后,再排序.
這能幫助程序明顯縮短執(zhí)行時間取逾。我們對清單 14 進行優(yōu)化:
// 優(yōu)化:排序前進行 limit 和 skip
List<Person> persons = new ArrayList();
for (int i = 1; i <= 5; i++) {
Person person = new Person(i, "name" + i);
persons.add(person);
}
List<Person> personList2 = persons.stream().limit(2).sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).collect(Collectors.toList());
System.out.println(personList2);
##>> distinct <<##
下面的例子則使用 distinct 來找出不重復的單詞耗绿。
// 找出全文的單詞,轉(zhuǎn)小寫砾隅,并排序
List<String> words = br.lines().
flatMap(line -> Stream.of(line.split(" "))).
filter(word -> word.length() > 0).
map(String::toLowerCase).
distinct().
sorted().
collect(Collectors.toList());
br.close();
System.out.println(words);
##>> Match <<##
Stream 有三個 match 方法缭乘,從語義上說:
allMatch:Stream 中全部元素符合傳入的 predicate,返回 true
anyMatch:Stream 中只要有一個元素符合傳入的 predicate琉用,返回 true
noneMatch:Stream 中沒有一個元素符合傳入的 predicate堕绩,返回 true
它們都不是要遍歷全部元素才能返回結(jié)果。例如 allMatch 只要一個元素不滿足條件邑时,就 skip 剩下的所有元素奴紧,返回 false。
// 使用 Match
List<Person> persons = new ArrayList();
persons.add(new Person(1, "name" + 1, 10));
persons.add(new Person(2, "name" + 2, 21));
persons.add(new Person(3, "name" + 3, 34));
persons.add(new Person(4, "name" + 4, 6));
persons.add(new Person(5, "name" + 5, 55));
boolean isAllAdult = persons.stream().
allMatch(p -> p.getAge() > 18);
System.out.println("All are adult? " + isAllAdult);
boolean isThereAnyChild = persons.stream().
anyMatch(p -> p.getAge() < 12);
System.out.println("Any child? " + isThereAnyChild);
// 輸出結(jié)果:
All are adult? false
Any child? true
五晶丘、總結(jié)
## 總之黍氮,Stream 的特性可以歸納為:
不是數(shù)據(jù)結(jié)構(gòu)
它沒有內(nèi)部存儲,它只是用操作管道從 source(數(shù)據(jù)結(jié)構(gòu)浅浮、數(shù)組沫浆、generator function、IO channel)抓取數(shù)據(jù)滚秩。
它也絕不修改自己所封裝的底層數(shù)據(jù)結(jié)構(gòu)的數(shù)據(jù)专执。例如 Stream 的 filter 操作會產(chǎn)生一個不包含被過濾元素的新 Stream,而不是從 source 刪除那些元素郁油。
所有 Stream 的操作必須以 lambda 表達式為參數(shù)
不支持索引訪問
你可以請求第一個元素本股,但無法請求第二個,第三個桐腌,或最后一個拄显。不過請參閱下一項。
很容易生成數(shù)組或者 List
惰性化
很多 Stream 操作是向后延遲的案站,一直到它弄清楚了最后需要多少數(shù)據(jù)才會開始躬审。
Intermediate 操作永遠是惰性化的。
并行能力
當一個 Stream 是并行化的蟆盐,就不需要再寫多線程代碼承边,所有對它的操作會自動并行進行的。
可以是無限的
集合有固定大小舱禽,Stream 則不必炒刁。limit(n) 和 findFirst() 這類的 short-circuiting 操作可以對無限的 Stream 進行運算并很快完成恩沽。