1. 概述
1.1 簡介
Java 8 中有兩大最為重要的改革,第一個是 Lambda 表達式,另外一個則是 Stream API(java.util.stream.*)。
Stream 是 Java 8 中處理集合的關鍵抽象概念,它可以指定你希望對集合進行的操作,可以執行非常復雜的查找、過濾和映射數據等操作。使用 Stream API 對集合數據進行,就類似于使用 SQL 執行的數據庫查詢。也可以使用 Stream API 來并行執行操作。簡而言之,Stream API 提供了一種高效且易于使用的處理數據的方式。
1.2 流(Stream)到底是什么呢?
是數據渠道,用于操作數據源(集合、數組等)所生成的元素序列。“集合講的是數據,流講的是計算”
Stream(流)是一個來自數據源的元素隊列并支持聚合操作
- 元素是特定類型的對象,形成一個隊列。 Java中的Stream并不會存儲元素,而是按需計算。
- 數據源 流的來源。 可以是集合,數組,I/O channel, 產生器generator 等。
- 聚合操作 類似SQL語句一樣的操作, 比如 filter, map, reduce, find, match, sorted 等。
和以前的 Collection 操作不同, Stream 操作還有兩個基礎的特征:
- Pipelining: 中間操作都會返回流對象本身。 這樣多個操作可以串聯成一個管道, 如同流式風格(fluent style)。 這樣做可以對操作進行優化, 比如延遲執行(laziness)和短路( short-circuiting)。
- 內部迭代: 以前對集合遍歷都是通過 Iterator 或者 For-Each 的方式, 顯式的在集合外部進行迭代, 這叫做外部迭代。 Stream提供了內部迭代的方式, 通過訪問者模式(Visitor)實現。
注意 :
- Stream 自己不會存儲元素
- Stream 不會改變源對象,相反,它們會返回一個持有結果的新 Stream
- Stream 操作時延遲執行的。這意味著它們會等到需要結果的時候才執行
1.3 Stream 操作的三個步驟
-
創建 Stream
- 一個數據源(集合、數組等),獲取一個流
-
中間操作(聚合操作)
- 一個中間操作鏈,對數據源的數據進行處理
-
終止操作(終端操作)
- 一個終止操作,執行中間操作鏈,并產生結果
2. 創建 Stream(流)
在 Java 8 中, 集合接口有兩個方法來生成流:
- stream() ? 為集合創建串行流。
- parallelStream() ? 為集合創建并行流。
創建 Stream 的 5 種方式
@Test
public void t1() {// 1. Collection 提供了兩個方法 stream() 與 parallelStream()List<String> list = new ArrayList<>();Stream<String> stream = list.stream(); //獲取一個順序流Stream<String> parallelStream = list.parallelStream(); //獲取一個并行流// 2. 通過 Arrays 中的 stream() 獲取一個數組流Integer[] nums = new Integer[10];Stream<Integer> stream1 = Arrays.stream(nums);// 3. 通過 Stream 類中靜態方法 of()Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);// 4. 創建無限流 - 迭代Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(20);stream3.forEach(System.out::println);// 5. 創建無限流 - 生成Stream<Double> stream4 = Stream.generate(Math::random).limit(5);stream4.forEach(System.out::println);
}
3. Stream 的中間操作
多個中間操作可以連接起來形成一個流水線,除非流水線上觸發終止操作,否則中間操作不會執行任何處理,而是在終止操作時一次性全部處理,稱為“惰性求值”
提供基礎的操作數據
List<Employee> emps = Arrays.asList(new Employee(1, "a1", 28, 3888.99),new Employee(2, "a2", 49, 336.66),new Employee(3, "a3", 18, 3323.33),new Employee(4, "a4", 38, 6666.77),new Employee(5, "a5", 8, 80.88),new Employee(5, "a5", 8, 80.88),new Employee(5, "a5", 8, 80.88),new Employee(6, "a6", 56, 100.66)
);
3.1 篩選與切片
-
filter
接收Lambda,從流中排除某些元素。 -
limit
截斷流,使元素不超過給定數量 -
skip(n)
跳過元素,返回一個扔掉了前 n 個元素的流,若流中元素不足 n 個,則返回一個空流,與 limit 互補 -
distinct
篩選去重,通過流所生成元素的hashCode()
和equals()
去除重復元素
1. filter 接收Lambda,從流中排除某些元素
@Test
public void t2() {// 中間操作:不會執行任何操作Stream<Employee> stream = emps.stream().filter((e) -> {System.out.println("中間操作");return e.getAge() > 20;});// 終止操作:一次性執行全部內容,即"惰性求值"stream.forEach(System.out::println);}
2. limit 截斷流
@Test
public void t3() {emps.stream().filter((e) -> {// 當達到 limit 為 2 時將不繼續遍歷,稱為短路,以提高效率System.out.println("短路");return e.getSalary() > 3000;}).limit(2).forEach(System.out::println);
}
3. skip 跳過元素
@Test
public void t4() {emps.stream().filter(e -> e.getSalary() > 100).skip(2).forEach(System.out::println);
}
4. distinct 篩選
@Test
public void t5() {emps.stream().distinct().forEach(System.out::println);
}
要使用 distinct
需要重寫 Employee
的 hashCode()
和 equals()
方法
@Override
public int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + id;result = prime * result + ((name == null) ? 0 : name.hashCode());long temp;temp = Double.doubleToLongBits(salary);result = prime * result + (int) (temp ^ (temp >>> 32));return result;
}@Override
public boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Employee other = (Employee) obj;if (age != other.age)return false;if (id != other.id)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))return false;return true;
}
3.2 映射
-
map
接收 Lambda,將元素轉換成其它形式或提取信息。接收一個函數作為參數,該函數會被應用到每個元素上,并將其映射成一個新的元素 -
flatMap
接收一個函數作為參數,將流中的每個值都換成另一個流,然后把所有流連接成一個流
1. map
將原有的元素進過函數處理,讓后映射(覆蓋)成一個新的元素
@Test
public void t6() {List<String> list = Arrays.asList("aa","bb","cc","dd");list.stream().map((s) -> s.toUpperCase()).forEach(System.out::println);System.out.println("------------------------------------");emps.stream().map(Employee::getName).forEach(System.out::println);
}
2. flatMap
基礎方法
/*** 將字符串分解成字符 list,并返回 Stream* * @param str 待分解字符串* @return Stream*/
public static Stream<Character> filterCharacter(String str) {List<Character> list = new ArrayList<>();for (Character ch : str.toCharArray()) {list.add(ch);}return list.stream();
}
正常情況下,當 filterCharacter
返回的也是一個 Stream
時,相當于流里面還有子流,接收的結果就是 Stream<Stream<Character>>
,如果我們要進行遍歷的話,就需要使用兩層 forEach
才能遍歷完成。
@Test
public void t7() {List<String> list = Arrays.asList("aa","bb","cc","dd");Stream<Stream<Character>> stream = list.stream().map(StreamTest1::filterCharacter);// 因為 Stream 還是 Stream 所以需要嵌套 forEach 才能進行遍歷stream.forEach((sm) -> {sm.forEach(System.out::println);});
}
但如果使用 flatMap
就可以將每個子流都合并成一個流,這樣遍歷的時候只使用一層 forEach
就可以了
@Test
public void t8() {List<String> list = Arrays.asList("aa","bb","cc","dd");Stream<Character> stream = list.stream().flatMap(StreamTest1::filterCharacter);stream.forEach(System.out::println);
}
3.3 排序
-
sorted
自然排序(Comparable) -
sorted(Comparator com)
定制排序(Comparator)
1. sorted 自然排序
@Test
public void t9() {List<String> list = Arrays.asList("cc","aa","dd","bb");list.stream().sorted().forEach(System.out::println);
}
2. sorted(Comparator com) 定制排序
@Test
public void t10() {emps.stream().sorted((e1,e2) -> Integer.compare(e1.getAge(),e2.getAge())).forEach(System.out::println);
}
4. Stream 終止操作
4.1 查找與匹配
-
allMatch
檢查是否匹配所有元素 -
anyMatch
檢查是否至少匹配一個元素 -
noneMatch
檢查是否沒有匹配的元素 -
findFirst
返回第一個元素 -
findAny
返回當前流中的任意元素 -
count
返回流中元素的總個數 -
max
返回流中最大值 -
min
返回流中最小值
基礎數據
List<Employee> emps = Arrays.asList(new Employee(1, "a1", 28, 3888.99, Employee.Status.BUSY),new Employee(2, "a2", 49, 336.66, Employee.Status.FREE),new Employee(3, "a3", 18, 3323.33, Employee.Status.VOCATION),new Employee(4, "a4", 38, 6666.77, Employee.Status.FREE),new Employee(5, "a5", 8, 80.88, Employee.Status.VOCATION),new Employee(6, "a6", 56, 100.66, Employee.Status.BUSY)
);
1. allMatch
檢查是否匹配所有元素
@Test
public void t1() {boolean bool = emps.stream().allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));System.out.println(bool);
}
2. anyMatch
檢查是否至少匹配一個元素
@Test
public void t2() {boolean bool = emps.stream().anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));System.out.println(bool);
}
3. noneMatch
檢查是否沒有匹配的元素
@Test
public void t3() {boolean bool = emps.stream().noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));System.out.println(bool);
}
4. findFirst
返回第一個元素
@Test
public void t4() {Optional<Employee> op = emps.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).findFirst();System.out.println(op.get());
}
5. findAny
返回當前流中的任意元素
@Test
public void t5() {Optional<Employee> op = emps.stream().filter((e) -> e.getStatus().equals(Employee.Status.FREE)).findAny();System.out.println(op.get());
}
6. count
返回流中元素的總個數
/*** 查詢空閑人數*/
@Test
public void t6() {Long count = emps.stream().filter((e) -> e.getStatus().equals(Employee.Status.FREE)).count();System.out.println("count : " + count);
}
7. max
返回流中最大值
/*** 查詢工資最高的人*/
@Test
public void t7() {Optional<Employee> op = emps.stream().max((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()));System.out.println(op.get());
}
8. min
返回流中最小值
/*** 獲取工資最少的人的工資*/
@Test
public void t8() {Optional<Double> op = emps.stream().map(Employee::getSalary).min(Double::compare);System.out.println(op.get());
}
4.2 規約(reduce)
-
T reduce(T identity, BinaryOperator<T> accumulator)
可以將流中的元素反復結合起來,得到一個值,返回 T -
Optional<T> reduce(BinaryOperator<T> accumulator)
可以將流中的元素反復結合起來,得到一個值,返回Optional<T>
備注:map 和 reduce 的連接通常稱為 map-reduce 模式,因 Google 用它來進行網絡搜索而出名
1. 實例
@Test
public void t9() {List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);Integer sum = list.stream().reduce(0, (x, y) -> x + y);System.out.println("sum : " + sum);
}
說明 :
首先將起始值 0 給 x,然后在流中取出一個元素 1 給了 y,然后 x y 相加結果為 1,再賦給 x,然后再取出一個元素 2 賦給y,然后 x y 相加結果為 3,以此類推
2. 實例
/*** 計算所有人工資的總和*/
@Test
public void t10() {Optional<Double> op = emps.stream().map(Employee::getSalary).reduce(Double::sum);System.out.println("Salary Sum : " + op.get());
}
4.3 收集(collect)
- collect 將流轉換為其它形式,接收一個 Collector(收集器) 接口的實現,用于給 Stream 中元素做匯總的方法
Collector 接口中方法的實現決定了如何對流執行收集操作(如收集到List、Set、Map)。但是 Collector 實現類提供了很多靜態方法,可以方便地創建常見收集器實例,具體方法與實例如下表:
1. 實例 - 將結果收集到 List、Set 等容器
@Test
public void t1() {List<String> list = emps.stream().map(Employee::getName).collect(Collectors.toList());list.forEach(System.out::println);System.out.println("------------------------------------------");Set<String> set = emps.stream().map(Employee::getName).collect(Collectors.toSet());set.forEach(System.out::println);System.out.println("------------------------------------------");HashSet<String> hs = emps.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));hs.forEach(System.out::println);
}
2. 實例 - 計算
@Test
public void t2() {Long count = emps.stream().collect(Collectors.counting());System.out.println("總數 : " + count);System.out.println("------------------------------------------");Double avg = emps.stream().collect(Collectors.averagingDouble(Employee::getSalary));System.out.println("工資平均值 : " + avg);System.out.println("------------------------------------------");Double sum = emps.stream().collect(Collectors.summingDouble(Employee::getSalary));System.out.println("工資總和 : " + sum);System.out.println("------------------------------------------");Optional<Employee> max = emps.stream().collect(Collectors.maxBy((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary())));System.out.println("工資最多的員工 : " + max.get());System.out.println("------------------------------------------");Optional<Double> min = emps.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));System.out.println("工資最少的員工 : " + min.get());}
3. 實例 - 計算的另一種實現方式
@Test
public void t6() {DoubleSummaryStatistics dss = emps.stream().collect(Collectors.summarizingDouble(Employee::getSalary));System.out.println("sum : " + dss.getSum());System.out.println("max : " + dss.getMax());System.out.println("avg : " + dss.getAverage());System.out.println("count : " + dss.getCount());System.out.println("min : " + dss.getMin());
}
4.4 分組
分組就相當于 SQL 語句中的 group by,按一個類別或多個類別進行分組
1. 實例
@Test
public void t3() {Map<Employee.Status, List<Employee>> map = emps.stream().collect(Collectors.groupingBy(Employee::getStatus));// 格式化輸出,方便查看Gson gson = new GsonBuilder().setPrettyPrinting().create();System.out.println(gson.toJson(map));
}
2. 實例 多級分組
@Test
public void t4() {Map<Employee.Status, Map<String, List<Employee>>> map = emps.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {if (e.getAge() <= 35) {return "青年";} else if (e.getAge() <= 50) {return "中年";} else {return "老年";}})));// 格式化輸出,方便查看Gson gson = new GsonBuilder().setPrettyPrinting().create();System.out.println(gson.toJson(map));
}
4.5 分區
分區是一種特殊的分組,結果 map 至少包含兩個不同的分組一個true,一個false
@Test
public void t5() {Map<Boolean,List<Employee>> map = emps.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() > 1000));// 格式化輸出,方便查看Gson gson = new GsonBuilder().setPrettyPrinting().create();System.out.println(gson.toJson(map));
}
4.6 連接
將結果進行連接
@Test
public void t8() {String s1 = emps.stream().map(Employee::getName).collect(Collectors.joining());System.out.println("連接 : " + s1);String s2 = emps.stream().map(Employee::getName).collect(Collectors.joining(","));System.out.println("添加中間分隔符 : " + s2);String s3 = emps.stream().map(Employee::getName).collect(Collectors.joining(",", "==", "=="));System.out.println("添加左右分隔符 : " + s3);
}
本文首發于凌風博客:Java 8 新特性之Stream API
作者:凌風