一、Stream流介紹
1.1 集合處理資料的弊端
當我們需要對集合中的元素進行操作的時候,除了必需的添加、删除、擷取外,最典型的就是集合周遊。我們來體驗 集合操作資料的弊端,需求如下:
一個ArrayList集合中存儲有以下資料:
張無忌,周芷若,趙敏,張強,張三豐
需求:
1.拿到所有姓張的
2.拿到名字長度為3個字的
3.列印這些資料
代碼如下:
public static void main(String[] args) {
// 一個ArrayList集合中存儲有以下資料:張無忌,周芷若,趙敏,張強,張三豐
// 需求:1.拿到所有姓張的 2.拿到名字長度為3個字的 3.列印這些資料
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "張無忌", "周芷若", "趙敏", "張強", "張三豐");
// 1.拿到所有姓張的
ArrayList<String> zhangList = new ArrayList<>(); // {"張無忌", "張強", "張三豐"}
for (String name : list) {
if (name.startsWith("張")) {
zhangList.add(name);
}
}
// 2.拿到名字長度為3個字的
ArrayList<String> threeList = new ArrayList<>(); // {"張無忌", "張三豐"}
for (String name : zhangList) {
if (name.length() == 3) {
threeList.add(name);
}
}
// 3.列印這些資料
for (String name : threeList) {
System.out.println(name);
}
}
循環周遊的弊端
這段代碼中含有三個循環,每一個作用不同:
- 首先篩選所有姓張的人;
- 然後篩選名字有三個字的人;
- 最後進行對結果進行列印輸出。
每當我們需要對集合中的元素進行操作的時候,總是需要進行循環、循環、再循環。這是理所當然的麼?不是。循環是做事情的方式,而不是目的。每個需求都要循環一次,還要搞一個新集合來裝資料,如果希望再次周遊,隻能再使 用另一個循環從頭開始。
那Stream能給我們帶來怎樣更加優雅的寫法呢?
Stream的更優寫法
下面來看一下借助Java 8的Stream API,修改後的代碼:
public class Demo03StreamFilter {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("張無忌");
list.add("周芷若");
list.add("趙敏");
list.add("張強");
list.add("張三豐");
list.stream()
.filter(s -> s.startsWith("張"))
.filter(s -> s.length() == 3)
.forEach(System.out::println);
}
}
直接閱讀代碼的字面意思即可完美展示無關邏輯方式的語義:擷取流、過濾姓張、過濾長度為3、逐一列印。我們真 正要做的事情内容被更好地展現在代碼中。
1.2 Stream流式思想概述
注意:Stream和IO流(InputStream/OutputStream)沒有任何關系,請暫時忘記對傳統IO流的固有印象!
Stream流式思想類似于工廠工廠中的房間的“生産流水線”,Stream流不是一種資料結構,不儲存資料,而是對資料進行加工 處理。Stream可以看作是流水線上的一個工序。在流水線上,通過多個工序讓一個原材料加工成一個商品。

Stream API能讓我們快速完成許多複雜的操作,如篩選、切片、映射、查找、去除重複,統計,比對和歸約。
1.3 小結
首先我們了解了集合操作資料的弊端,每次都需要循環周遊,還要建立新集合,很麻煩
Stream是流式思想,相當于工廠的流水線,對集合中的資料進行加工處理
二、擷取Stream流的兩種方式
擷取一個流非常簡單,有以下幾種常用的方式:
- 所有的 Collection 集合都可以通過 stream 預設方法擷取流;
- Stream 接口的靜态方法 of 可以擷取數組對應的流。
2.1 根據Collection擷取流
首先, java.util.Collection 接口中加入了default方法 stream 用來擷取流,是以其所有實作類均可擷取流。
public interface Collection {
default Stream<E> stream()
}
import java.util.*;
import java.util.stream.Stream;
public class Demo04GetStream {
public static void main(String[] args) {
// 集合擷取流
// Collection接口中的方法: default Stream<E> stream() 擷取流
List<String> list = new ArrayList<>();
// ...
Stream<String> stream1 = list.stream();
Set<String> set = new HashSet<>();
// ...
Stream<String> stream2 = set.stream();
Vector<String> vector = new Vector<>();
// ...
Stream<String> stream3 = vector.stream();
}
}
java.util.Map 接口不是 Collection 的子接口,是以擷取對應的流需要分key、value或entry等情況:
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class Demo05GetStream {
public static void main(String[] args) {
// Map擷取流
Map<String, String> map = new HashMap<>();
// ...
Stream<String> keyStream = map.keySet().stream();
Stream<String> valueStream = map.values().stream();
Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream();
}
}
2.2 Stream中的靜态方法of擷取流
由于數組對象不可能添加預設方法,是以 Stream 接口中提供了靜态方法 of ,使用很簡單:
import java.util.stream.Stream;
public class Demo06GetStream {
public static void main(String[] args) {
// Stream中的靜态方法: static Stream of(T... values)
Stream<String> stream6 = Stream.of("aa", "bb", "cc");
String[] arr = {"aa", "bb", "cc"};
Stream<String> stream7 = Stream.of(arr);
Integer[] arr2 = {11, 22, 33};
Stream<Integer> stream8 = Stream.of(arr2);
// 注意:基本資料類型的數組不行
int[] arr3 = {11, 22, 33};
Stream<int[]> stream9 = Stream.of(arr3);
}
}
備注: of 方法的參數其實是一個可變參數,是以支援數組。
三、Stream常用方法和注意事項
3.1 Stream常用方法
Stream流模型的操作很豐富,這裡介紹一些常用的API。這些方法可以被分成兩種:
- 終結方法:傳回值類型不再是Stream 類型的方法,不再支援鍊式調用。本小節中,終結方法包括count 和forEach 方法。
- 非終結方法:傳回值類型仍然是Stream 類型的方法,支援鍊式調用。(除了終結方法外,其餘方法均為非終結方法。)
- 對比Spark的兩種算子
備注:本小節之外的更多方法,請自行參考API文檔。
3.2 Stream注意事項(重要)
- Stream隻能操作一次
- Stream方法傳回的是新的流
- Stream不調用終結方法,中間的操作不會執行
3.3 forEach方法
forEach 用來周遊流中的資料
void forEach(Consumer<? super T> action);
該方法接收一個 Consumer 接口函數,會将每一個流元素交給該函數進行處理。例如:
@Test
public void testForEach() {
List<String> one = new ArrayList<>();
Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子");
/*one.stream().forEach((String s) -> {
System.out.println(s);
});*/
// 簡寫
// one.stream().forEach(s -> System.out.println(s));
one.stream().forEach(System.out::println);
}
3.4 count方法
Stream流提供 count 方法來統計其中的元素個數 :
long count();
該方法傳回一個long值代表元素個數。基本使用:
@Test
public void testCount() {
List<String> one = new ArrayList<>();
Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子");
System.out.println(one.stream().count());
}
3.5 filter方法
Java Stream
filter用于過濾資料,傳回符合過濾條件的資料
可以通過 filter 方法将一個流轉換成另一個子集流。方法聲明:
Stream<T> filter(Predicate<? super T> predicate);
該接口接收一個 Predicate 函數式接口參數(可以是一個Lambda或方法引用)作為篩選條件。
Stream流中的 filter 方法基本使用的代碼如:
@Test
public void testFilter() {
List<String> one = new ArrayList<>();
Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子");
one.stream()
.filter(s -> s.length() == 2)
.forEach(System.out::println);
}
在這裡通過Lambda表達式來指定了篩選的條件:姓名長度為2個字。
3.6 limit方法
Java Stream
limit 方法可以對流進行截取,隻取用前n個。方法簽名:
Stream<T> limit(long maxSize);
參數是一個long型,如果集合目前長度大于參數則進行截取。否則不進行操作。基本使用:
@Test
public void testLimit() {
List<String> one = new ArrayList<>();
Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子");
one.stream().limit(3).forEach(System.out::println);
}
3.7 skip方法
Java Stream
如果希望跳過前幾個元素,可以使用 skip 方法擷取一個截取之後的新流:
Stream<T> skip(long n);
如果流的目前長度大于n,則跳過前n個;否則将會得到一個長度為0的空流。基本使用:
@Test
public void testSkip() {
List<String> one = new ArrayList<>();
Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子");
one.stream().skip(2).forEach(System.out::println);
}
3.8 map方法
Java Stream
如果需要将流中的元素映射到另一個流中,可以使用 map 方法。方法簽名:
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
該接口需要一個 Function 函數式接口參數,可以将目前流中的T類型資料轉換為另一種R類型的流。
Stream流中的 map 方法基本使用的代碼如:
@Test
public void testMap() {
Stream<String> original = Stream.of("11", "22", "33");
original.map(Integer::parseInt).forEach(System.out::println);
List<HdInfo> hdInfos = hdInfoMapper.selectByExample(example);
//鍊式調用需要在類上設定這個注解@Accessors(chain = true)
hdInfos.stream().map(item->item.setTypeName(publicPortService.selectHdTypeById(item.getTypeId()).getName())).collect(Collectors.toList());
}
這段代碼中, map 方法的參數通過方法引用,将字元串類型轉換成為了int類型(并自動裝箱為 Integer 類對象)。
3.9 sorted方法
如果需要将資料排序,可以使用 sorted 方法。方法簽名:
Stream<T> sorted();
Stream<T> sorted(Comparator<? super T> comparator);
基本使用
Stream流中的 sorted 方法基本使用的代碼如:
@Test
public void testSorted() {
// sorted(): 根據元素的自然順序排序
// sorted(Comparator<? super T> comparator): 根據比較器指定的規則排序
Stream.of(33, 22, 11, 55)
.sorted()
.sorted((o1, o2) -> o2 - o1)
.forEach(System.out::println);
}
這段代碼中, sorted 方法根據元素的自然順序排序,也可以指定比較器排序。
3.10 distinct方法
Java Stream
如果需要去除重複資料,可以使用 distinct 方法。方法簽名:
Stream<T> distinct();
基本使用
Stream流中的 distinct 方法基本使用的代碼如:
@Test
public void testDistinct() {
Stream.of(22, 33, 22, 11, 33)
.distinct()
.forEach(System.out::println);
}
如果是自定義類型如何是否也能去除重複的資料呢?
@Test
public void testDistinct2() {
Stream.of(
new Person("劉德華", 58),
new Person("張學友", 56),
new Person("張學友", 56),
new Person("黎明", 52))
.distinct()
.forEach(System.out::println);
}
public class Person {
private String name;
private int age;
// 省略其他
}
自定義類型是根據對象的hashCode和equals來去除重複元素的。
3.11match方法
如果需要判斷資料是否比對指定的條件,可以使用 Match 相關方法。方法簽名:
boolean allMatch(Predicate<? super T> predicate);
boolean anyMatch(Predicate<? super T> predicate);
boolean noneMatch(Predicate<? super T> predicate)
基本使用
Stream流中的 Match 相關方法基本使用的代碼如:
@Test
public void testMatch() {
boolean b = Stream.of(5, 3, 6, 1)
// .allMatch(e -> e > 0); // allMatch: 元素是否全部滿足條件
// .anyMatch(e -> e > 5); // anyMatch: 元素是否任意有一個滿足條件
.noneMatch(e -> e < 0); // noneMatch: 元素是否全部不滿足條件
System.out.println("b = " + b);
}
3.12 find方法
Java Stream
如果需要找到某些資料,可以使用 find 相關方法。方法簽名:
Optional<T> findFirst();
Optional<T> findAny();
基本使用
Stream流中的 find 相關方法基本使用的代碼如:
@Test
public void testFind() {
Optional<Integer> first = Stream.of(5, 3, 6, 1).findFirst();
System.out.println("first = " + first.get());
Optional<Integer> any = Stream.of(5, 3, 6, 1).findAny();
System.out.println("any = " + any.get());
}
3.13 max和min方法
Java Stream
如果需要擷取最大和最小值,可以使用 max 和 min 方法。方法簽名:
Optional<T> max(Comparator<? super T> comparator);
Optional<T> min(Comparator<? super T> comparator);
基本使用
Stream流中的 max 和 min 相關方法基本使用的代碼如:
@Test
public void testMax_Min() {
Optional<Integer> max = Stream.of(5, 3, 6, 1).max((o1, o2) -> o1 - o2);
System.out.println("first = " + max.get());
Optional<Integer> min = Stream.of(5, 3, 6, 1).min((o1, o2) -> o1 - o2);
System.out.println("any = " + min.get());
}
3.14 reduce方法
Java Stream
如果需要将所有資料歸納得到一個資料,可以使用 reduce 方法。方法簽名:
T reduce(T identity, BinaryOperator<T> accumulator);
基本使用
Stream流中的 reduce 相關方法基本使用的代碼如:
@Test
public void testReduce() {
int reduce = Stream.of(4, 5, 3, 9)
.reduce(0, (a, b) -> {
System.out.println("a = " + a + ", b = " + b);return a + b;
});
// reduce:
// 第一次将預設做指派給x, 取出第一個元素指派給y,進行操作
// 第二次,将第一次的結果指派給x, 取出二個元素指派給y,進行操作
// 第三次,将第二次的結果指派給x, 取出三個元素指派給y,進行操作
// 第四次,将第三次的結果指派給x, 取出四個元素指派給y,進行操作
System.out.println("reduce = " + reduce);
// 化簡
int reduce2 = Stream.of(4, 5, 3, 9)
.reduce(0, (x, y) -> {return Integer.sum(x, y);});
// 進一步化簡
int reduce3 = Stream.of(4, 5, 3, 9).reduce(0, Integer::sum);
int max = Stream.of(4, 5, 3, 9)
.reduce(0, (x, y) -> {
return x > y ? x : y;
});
System.out.println("max = " + max);
}
x = 0, y = 4
x = 4, y = 5
x = 9, y = 3
x = 12, y = 9
reduce = 21
max = 9
3.15 map和reduce組合使用
@Test
public void testMapReduce() {
// 求出所有年齡的總和
int totalAge = Stream.of(
new Person("劉德華", 58),
new Person("張學友", 56),
new Person("郭富城", 54),
new Person("黎明", 52))
.map((p) -> p.getAge())
.reduce(0, (x, y) -> x + y);
System.out.println("totalAge = " + totalAge);
// 找出最大年齡
int maxAge = Stream.of(
new Person("劉德華", 58),
new Person("張學友", 56),
new Person("郭富城", 54),
new Person("黎明", 52))
.map((p) -> p.getAge())
.reduce(0, (x, y) -> x > y ? x : y);
System.out.println("maxAge = " + maxAge);
// 統計 數字2 出現的次數
int count = Stream.of(1, 2, 2, 1, 3, 2)
.map(i -> {
if (i == 2) {
return 1;
} else {
return 0;
}
})
.reduce(0, Integer::sum);
System.out.println("count = " + count);
}
3.16 mapToIn
Java Stream
如果需要将Stream中的Integer類型資料轉成int類型,可以使用 mapToInt 方法。方法簽名:
IntStream mapToInt(ToIntFunction<? super T> mapper);
Stream流中的 mapToInt 相關方法基本使用的代碼如:
@Test
public void test1() {
// Integer占用的記憶體比int多,在Stream流操作中會自動裝箱和拆箱
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5});
// 把大于3的和列印出來
// Integer result = stream
// .filter(i -> i.intValue() > 3)
// .reduce(0, Integer::sum);
// System.out.println(result);
// 先将流中的Integer資料轉成int,後續都是操作int類型
IntStream intStream = stream.mapToInt(Integer::intValue);
int reduce = intStream
.filter(i -> i > 3)
.reduce(0, Integer::sum);
System.out.println(reduce);
// 将IntStream轉化為Stream<Integer>
IntStream intStream1 = IntStream.rangeClosed(1, 10);
Stream<Integer> boxed = intStream1.boxed();
boxed.forEach(s -> System.out.println(s.getClass() + ", " + s));
}
3.17 concat方法
如果有兩個流,希望合并成為一個流,那麼可以使用 Stream 接口的靜态方法 concat :
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
備注:這是一個靜态方法,與 java.lang.String 當中的 concat 方法是不同的。
該方法的基本使用代碼如:
@Test
public void testContact() {
Stream<String> streamA = Stream.of("張三");
Stream<String> streamB = Stream.of("李四");
Stream<String> result = Stream.concat(streamA, streamB);
result.forEach(System.out::println);
}
3.18 Stream綜合案例
現在有兩個 ArrayList 集合存儲隊伍當中的多個成員姓名,要求使用傳統的for循環(或增強for循環)依次進行以下 若幹操作步驟:
- 第一個隊伍隻要名字為3個字的成員姓名;
- 第一個隊伍篩選之後隻要前3個人;
- 第二個隊伍隻要姓張的成員姓名;
- 第二個隊伍篩選之後不要前2個人;
- 将兩個隊伍合并為一個隊伍;
- 根據姓名建立 Person 對象;
- 列印整個隊伍的Person對象資訊。
兩個隊伍(集合)的代碼如下:
public class DemoArrayListNames {
public static void main(String[] args) {
List<String> one = List.of("迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子", "洪七公");
List<String> two = List.of("古力娜紮", "張無忌", "張三豐", "趙麗穎", "張二狗", "張天愛","張三");
// ....
}
}
而 Person 類的代碼為:
public class Person {
private String name;
public Person() {}
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{name='" + name + "'}";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
傳統方式
使用for循環 , 示例代碼:
public class DemoArrayListNames {
public static void main(String[] args) {
List<String> one = List.of("迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子", "洪七公");
List<String> two = List.of("古力娜紮", "張無忌", "張三豐", "趙麗穎", "張二狗", "張天愛", "張三");
// 第一個隊伍隻要名字為3個字的成員姓名;
List<String> oneA = new ArrayList<>();
for (String name : one) {
if (name.length() == 3) {
oneA.add(name);
}
}
// 第一個隊伍篩選之後隻要前3個人;
List<String> oneB = new ArrayList<>();
for (int i = 0; i < 3; i++) {
oneB.add(oneA.get(i));
}
// 第二個隊伍隻要姓張的成員姓名;
List<String> twoA = new ArrayList<>();
for (String name : two) {
if (name.startsWith("張")) {
twoA.add(name);
}
}
// 第二個隊伍篩選之後不要前2個人;
List<String> twoB = new ArrayList<>();
for (int i = 2; i < twoA.size(); i++) {
twoB.add(twoA.get(i));
}
// 将兩個隊伍合并為一個隊伍;
List<String> totalNames = new ArrayList<>();
totalNames.addAll(oneB);
totalNames.addAll(twoB);
// 根據姓名建立Person對象;
List<Person> totalPersonList = new ArrayList<>();
for (String name : totalNames) {
totalPersonList.add(new Person(name));
}
// 列印整個隊伍的Person對象資訊。
for (Person person : totalPersonList) {
System.out.println(person);
}
}
}
運作結果為:
Person{name='宋遠橋'}
Person{name='蘇星河'}
Person{name='洪七公'}
Person{name='張二狗'}
Person{name='張天愛'}
Person{name='張三'}
Stream方式
等效的Stream流式處理代碼為:
public class DemoStreamNames {
public static void main(String[] args) {
List<String> one = List.of("迪麗熱巴", "宋遠橋", "蘇星河", "老子", "莊子", "孫子", "洪七公");
List<String> two = List.of("古力娜紮", "張無忌", "張三豐", "趙麗穎", "張二狗", "張天愛", "張三");
// 第一個隊伍隻要名字為3個字的成員姓名;
// 第一個隊伍篩選之後隻要前3個人;
Stream<String> streamOne = one.stream().filter(s -> s.length() == 3).limit(3);
// 第二個隊伍隻要姓張的成員姓名;
// 第二個隊伍篩選之後不要前2個人;
Stream<String> streamTwo = two.stream().filter(s -> s.startsWith("張")).skip(2);
// 将兩個隊伍合并為一個隊伍;
// 根據姓名建立Person對象;
// 列印整個隊伍的Person對象資訊。
Stream.concat(streamOne, streamTwo).map(Person::new).forEach(System.out::println);
}
}
運作效果完全一樣:
Person{name='宋遠橋'}
Person{name='蘇星河'}
Person{name='洪七公'}
Person{name='張二狗'}
Person{name='張天愛'}
Person{name='張三'}
四、收集Stream流中的結果
對流操作完成之後,如果需要将流的結果儲存到數組或集合中,可以收集流中的資料
4.1 Stream流中的結果到集合中
Stream流提供 collect 方法,其參數需要一個 java.util.stream.Collector 接口對象來指定收集到哪 種集合中。java.util.stream.Collectors 類提供一些方法,可以作為 Collector`接口的執行個體:
public static Collector> toList() :轉換為 List 集合。
public static Collector> toSet() :轉換為 Set 集合。
下面是這兩個方法的基本使用代碼:
// 将流中資料收集到集合中
@Test
public void testStreamToCollection() {
Stream<String> stream = Stream.of("aa", "bb", "cc");
// List<String> list = stream.collect(Collectors.toList());
// Set<String> set = stream.collect(Collectors.toSet());
ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
}
4.2 Stream流中的結果到數組中
Stream提供 toArray 方法來将結果放到一個數組中,傳回值類型是Object[]的:
Object[] toArray();
其使用場景如:
@Test
public void testStreamToArray() {
Stream<String> stream = Stream.of("aa", "bb", "cc");
// Object[] objects = stream.toArray();
// for (Object obj : objects) {
// System.out.println();
// }
String[] strings = stream.toArray(String[]::new);
for (String str : strings) {
System.out.println(str);
}
}
4.3 對流中資料進行聚合計算
當我們使用Stream流處理資料後,可以像資料庫的聚合函數一樣對某個字段進行操作。比如擷取最大值,擷取最小 值,求總和,平均值,統計數量。
@Test
public void testStreamToOther() {
Stream<Student> studentStream = Stream.of(
new Student("趙麗穎", 58, 95),
new Student("楊穎", 56, 88),
new Student("迪麗熱巴", 56, 99),
new Student("柳岩", 52, 77));
// 擷取最大值
Optional<Student> collect = studentStream.collect(Collectors.maxBy((o1, o2) ->
o1.getSocre() - o2.getSocre()));
// 擷取最小值
Optional<Student> collect = studentStream.collect(Collectors.minBy((o1, o2) ->
o1.getSocre() - o2.getSocre()));
// System.out.println(collect.get());
// 求總和
int sumAge = studentStream.collect(Collectors.summingInt(s -> s.getAge()));
System.out.println("sumAge = " + sumAge);
//平均值
double avgScore = studentStream.collect(Collectors.averagingInt(s -> s.getSocre()));
System.out.println("avgScore = " + avgScore);
// 統計數量
Long count = studentStream.collect(Collectors.counting());
System.out.println("count = " + count);
}
4.4 對流中資料進行分組
當我們使用Stream流處理資料後,可以根據某個屬性将資料分組:
// 分組
@Test
public void testGroup() {
Stream<Student> studentStream = Stream.of(
new Student("趙麗穎", 52, 95),
new Student("楊穎", 56, 88),
new Student("迪麗熱巴", 56, 55),
new Student("柳岩", 52, 33));
// Map<Integer, List<Student>> map = studentStream.collect(Collectors.groupingBy(Student::getAge));
// 将分數大于60的分為一組,小于60分成另一組
Map<String, List<Student>> map = studentStream.collect(Collectors.groupingBy((s) ->{
if (s.getSocre() > 60) {
return "及格";
}else {
return "不及格";
}
}));
map.forEach((k, v) -> {
System.out.println(k + "::" + v);
});
}
效果:
不及格::[Student{name='迪麗熱巴', age=56, socre=55}, Student{name='柳岩', age=52, socre=33}]
及格::[Student{name='趙麗穎', age=52, socre=95}, Student{name='楊穎', age=56, socre=88}]
4.5 對流中資料進行多級分組
還可以對資料進行多級分組:
// 多級分組
@Test
public void testCustomGroup() {
Stream<Student> studentStream = Stream.of(
new Student("趙麗穎", 52, 95),
new Student("楊穎", 56, 88),
new Student("迪麗熱巴", 56, 99),
new Student("柳岩", 52, 77));
Map<Integer, Map<String, List<Student>>> map =
studentStream.collect(Collectors.groupingBy(s -> s.getAge(), Collectors.groupingBy(s -> {
if (s.getSocre() >= 90) {
return "優秀";
} else if (s.getSocre() >= 80 && s.getSocre() < 90) {
return "良好";
} else if (s.getSocre() >= 80 && s.getSocre() < 80) {
return "及格";
} else {
return "不及格";
}
})));
map.forEach((k, v) -> {
System.out.println(k + " == " + v);
});
}
效果:
52 == {不及格=[Student{name='柳岩', age=52, socre=77}], 優秀=[Student{name='趙麗穎', age=52,
socre=95}]}
56 == {優秀=[Student{name='迪麗熱巴', age=56, socre=99}], 良好=[Student{name='楊穎', age=56,
socre=88}]}
4.6 對流中資料進行分區
Java Stream
Collectors.partitioningBy 會根據值是否為true,把集合分割為兩個清單,一個true清單,一個false清單。
// 分區
@Test
public void testPartition() {
Stream<Student> studentStream = Stream.of(
new Student("趙麗穎", 52, 95),
new Student("楊穎", 56, 88),
new Student("迪麗熱巴", 56, 99),
new Student("柳岩", 52, 77));
// partitioningBy會根據值是否為true,把集合分割為兩個清單,一個true清單,一個false清單。
Map<Boolean, List<Student>> map = studentStream.collect(Collectors.partitioningBy(s ->s.getSocre() > 90));
map.forEach((k, v) -> {
System.out.println(k + " == " + v);
});
}
效果:
false == [Student{name='楊穎', age=56, socre=88}, Student{name='柳岩', age=52, socre=77}]
true == [Student{name='趙麗穎', age=52, socre=95}, Student{name='迪麗熱巴', age=56, socre=99}]
4.7 對流中資料進行拼接
// 拼接
@Test
public void testJoining() {
Stream<Student> studentStream = Stream.of(
new Student("趙麗穎", 52, 95),
new Student("楊穎", 56, 88),
new Student("迪麗熱巴", 56, 99),
new Student("柳岩", 52, 77));
String collect = studentStream
.map(Student::getName)
.collect(Collectors.joining(">_<", "^_^", "^v^"));
System.out.println(collect);
}
效果:
^_^趙麗穎>_<楊穎>_<迪麗熱巴>_<柳岩^v^
五、并行的Stream流
5.1 串行的Stream流
目前我們使用的Stream流是串行的,就是在一個線程上執行。
@Test
public void test0Serial() {
long count = Stream.of(4, 5, 3, 9, 1, 2, 6)
.filter(s -> {
System.out.println(Thread.currentThread() + ", s = " + s);
return true;
})
.count();
System.out.println("count = " + count);
}
效果:
Thread[main,5,main], s = 4
Thread[main,5,main], s = 5
Thread[main,5,main], s = 3
Thread[main,5,main], s = 9
Thread[main,5,main], s = 1
Thread[main,5,main], s = 2
Thread[main,5,main], s = 6
5.2 并行的Stream流
parallelStream其實就是一個并行執行的流。它通過預設的ForkJoinPool,可能提高多線程任務的速度。
擷取并行Stream流的兩種方式
- 直接擷取并行的流
- 将串行流轉成并行流
@Test
public void testgetParallelStream() {
ArrayList<Integer> list = new ArrayList<>();
// 直接擷取并行的流
Stream<Integer> stream = list.parallelStream();
// 将串行流轉成并行流
Stream<Integer> stream = list.stream().parallel();
}
并行操作代碼:
@Test
public void test0Parallel() {
long count = Stream.of(4, 5, 3, 9, 1, 2, 6)
.parallel() // 将流轉成并發流,Stream處理的時候将才去
.filter(s -> {
System.out.println(Thread.currentThread() + ", s = " + s);
return true;
})
.count();
System.out.println("count = " + count);
}
效果:
Thread[ForkJoinPool.commonPool-worker-13,5,main], s = 3
Thread[ForkJoinPool.commonPool-worker-19,5,main], s = 6
Thread[main,5,main], s = 1
Thread[ForkJoinPool.commonPool-worker-5,5,main], s = 5
Thread[ForkJoinPool.commonPool-worker-23,5,main], s = 4
Thread[ForkJoinPool.commonPool-worker-27,5,main], s = 2
Thread[ForkJoinPool.commonPool-worker-9,5,main], s = 9
count = 7
5.3 并行和串行Stream流的效率對比
使用for循環,串行Stream流,并行Stream流來對5億個數字求和。看消耗的時間。
public class Demo06 {
private static long times = 50000000000L;
private long start;
@Before
public void init() {
start = System.currentTimeMillis();
}
@After
public void destory() {
long end = System.currentTimeMillis();
System.out.println("消耗時間: " + (end - start));
}
// 測試效率,parallelStream 120
@Test
public void parallelStream() {
System.out.println("serialStream");
LongStream.rangeClosed(0, times)
.parallel()
.reduce(0, Long::sum);
}
// 測試效率,普通Stream 342
@Test
public void serialStream() {
System.out.println("serialStream");
LongStream.rangeClosed(0, times)
.reduce(0, Long::sum);
}
// 測試效率,正常for循環 421
@Test
public void forAdd() {
System.out.println("forAdd");
long result = 0L;
for (long i = 1L; i < times; i++) {
result += i;
}
}
}
我們可以看到parallelStream的效率是最高的。
Stream并行處理的過程會分而治之,也就是将一個大任務切分成多個小任務,這表示每個任務都是一個操作。
5.4 parallelStream線程安全問題
解決parallelStream線程安全問題
// 并行流注意事項
@Test
public void parallelStreamNotice() {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i);
}
List<Integer> newList = new ArrayList<>();
// 使用并行的流往集合中添加資料
list.parallelStream()
.forEach(s -> {
newList.add(s);
});
System.out.println("newList = " + newList.size());
}
運作效果:
newList = 903