Java8 Stream:2萬字20個例項,玩轉集合的篩選、歸約、分組、聚合
先貼上幾個案例,水平高超的同學可以挑戰一下:
-
從員工集合中篩選出salary大於8000的員工,並放置到新的集合裡。
-
統計員工的最高薪資、平均薪資、薪資之和。
-
將員工按薪資從高到低排序,同樣薪資者年齡小者在前。
-
將員工按性別分類,將員工按性別和地區分類,將員工按薪資是否高於8000分為兩部分。
用傳統的迭代處理也不是很難,但程式碼就顯得冗餘了,跟Stream相比高下立判。
1 Stream概述
Java 8 是一個非常成功的版本,這個版本新增的Stream
,配合同版本出現的Lambda
,給我們操作集合(Collection)提供了極大的便利。
那麼什麼是Stream
?
Stream
Stream API
對流中的元素進行操作,比如:篩選、排序、聚合等。
Stream
可以由陣列或集合建立,對流的操作分為兩種:
-
中間操作,每次返回一個新的流,可以有多個。
-
終端操作,每個流只能進行一次終端操作,終端操作結束後流無法再次使用。終端操作會產生一個新的集合或值。
另外,Stream
有幾個特性:
-
stream不儲存資料,而是按照特定的規則對資料進行計算,一般會輸出結果。
-
stream不會改變資料來源,通常情況下會產生一個新的集合或一個值。
-
stream具有延遲執行特性,只有呼叫終端操作時,中間操作才會執行。
2 Stream的建立
Stream
可以通過集合陣列建立。
1、通過java.util.Collection.stream()
方法用集合建立流
List<String> list = Arrays.asList("a", "b", "c"); // 建立一個順序流 Stream<String> stream = list.stream(); // 建立一個並行流 Stream<String> parallelStream = list.parallelStream();
2、使用java.util.Arrays.stream(T[] array)
方法用陣列建立流
int[] array={1,3,5,6,8}; IntStream stream= Arrays.stream(array);
3、使用Stream
的靜態方法:of()、iterate()、generate()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6); Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 3).limit(4); stream2.forEach(System.out::println); // 0 2 4 6 8 10 Stream<Double> stream3 = Stream.generate(Math::random).limit(3); stream3.forEach(System.out::println);
輸出結果:
0 3 6 9
0.6796156909271994
0.1914314208854283
0.8116932592396652
stream
和parallelStream
的簡單區分:stream
是順序流,由主執行緒按順序對流執行操作,而parallelStream
是並行流,內部以多執行緒並行執行的方式對流進行操作,但前提是流中的資料處理沒有順序要求。例如篩選集合中的奇數,兩者的處理不同之處:
如果流中的資料量足夠大,並行流可以加快處速度。
除了直接建立並行流,還可以通過parallel()
把順序流轉換成並行流:
Optional<Integer> findFirst = list.stream().parallel().filter(x->x>6).findFirst();
3 Stream的使用
在使用stream之前,先理解一個概念:Optional
。
案例使用的員工類
List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, "male", "New York")); personList.add(new Person("Jack", 7000, "male", "Washington")); personList.add(new Person("Lily", 7800, "female", "Washington")); personList.add(new Person("Anni", 8200, "female", "New York")); personList.add(new Person("Owen", 9500, "male", "New York")); personList.add(new Person("Alisa", 7900, "female", "New York")); class Person { private String name; // 姓名 private int salary; // 薪資 private int age; // 年齡 private String sex; //性別 private String area; // 地區 // 構造方法 public Person(String name, int salary, int age,String sex,String area) { this.name = name; this.salary = salary; this.age = age; this.sex = sex; this.area = area; } // 省略了get和set,請自行新增 }
3.1 遍歷/匹配(foreach/find/match)
/ import已省略,請自行新增,後面程式碼亦是 public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1); // 遍歷輸出符合條件的元素 list.stream().filter(x -> x > 6).forEach(System.out::println); // 匹配第一個 Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst(); // 匹配任意(適用於並行流) Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny(); // 是否包含符合特定條件的元素 boolean anyMatch = list.stream().anyMatch(x -> x < 6); System.out.println("匹配第一個值:" + findFirst.get()); System.out.println("匹配任意一個值:" + findAny.get()); System.out.println("是否存在大於6的值:" + anyMatch); } }
3.2 篩選(filter)
案例一:篩選出Integer
集合中大於7的元素,並打印出來
public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2, 9); Stream<Integer> stream = list.stream(); stream.filter(x -> x > 7).forEach(System.out::println); } }
案例二:篩選員工中工資高於8000的人,並形成新的集合。形成新集合依賴collect
(收集),後文有詳細介紹。
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York")); List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName) .collect(Collectors.toList()); System.out.print("高於8000的員工姓名:" + fiterList); } }
執行結果:
高於8000的員工姓名:[Tom, Anni, Owen]
3.3 聚合(max/min/count)
案例一:獲取String
集合中最長的元素。
public class StreamTest { public static void main(String[] args) { List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd"); Optional<String> max = list.stream().max(Comparator.comparing(String::length)); System.out.println("最長的字串:" + max.get()); } }
案例二:獲取Integer
集合中的最大值。
public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6); // 自然排序 Optional<Integer> max = list.stream().max(Integer::compareTo); // 自定義排序 Optional<Integer> max2 = list.stream().max(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); System.out.println("自然排序的最大值:" + max.get()); System.out.println("自定義排序的最大值:" + max2.get()); } }
輸出結果:
自然排序的最大值:11
自定義排序的最大值:11
案例三:獲取員工工資最高的人。
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York")); Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary)); System.out.println("員工工資最大值:" + max.get().getSalary()); } }
輸出結果:
員工工資最大值:9500
案例四:計算Integer
集合中大於6的元素的個數。
import java.util.Arrays; import java.util.List; public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9); long count = list.stream().filter(x -> x > 6).count(); System.out.println("list中大於6的元素個數:" + count); } }
輸出結果:
list中大於6的元素個數:4
3.4 對映(map/flatMap)
對映,可以將一個流的元素按照一定的對映規則對映到另一個流中。分為map
和flatMap
:
-
map
:接收一個函式作為引數,該函式會被應用到每個元素上,並將其對映成一個新的元素。 -
flatMap
:接收一個函式作為引數,將流中的每個值都換成另一個流,然後把所有流連線成一個流。
案例一:英文字串陣列的元素全部改為大寫。整數陣列每個元素+3。
public class StreamTest { public static void main(String[] args) { String[] strArr = { "abcd", "bcdd", "defde", "fTr" }; List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList()); List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11); List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList()); System.out.println("每個元素大寫:" + strList); System.out.println("每個元素+3:" + intListNew); } }
輸出結果:
每個元素大寫:[ABCD, BCDD, DEFDE, FTR]
每個元素+3:[4, 6, 8, 10, 12, 14]
案例二:將員工的薪資全部增加1000。
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York")); // 不改變原來員工集合的方式 List<Person> personListNew = personList.stream().map(person -> { Person personNew = new Person(person.getName(), 0, 0, null, null); personNew.setSalary(person.getSalary() + 10000); return personNew; }).collect(Collectors.toList()); System.out.println("一次改動前:" + personList.get(0).getName() + "-->" + personList.get(0).getSalary()); System.out.println("一次改動後:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary()); // 改變原來員工集合的方式 List<Person> personListNew2 = personList.stream().map(person -> { person.setSalary(person.getSalary() + 10000); return person; }).collect(Collectors.toList()); System.out.println("二次改動前:" + personList.get(0).getName() + "-->" + personListNew.get(0).getSalary()); System.out.println("二次改動後:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary()); } }
輸出結果:
一次改動前:Tom–>8900 一次改動後:Tom–>18900 二次改動前:Tom–>18900 二次改動後:Tom–>18900
案例三:將兩個字元數組合併成一個新的字元陣列。
public class StreamTest { public static void main(String[] args) { List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7"); List<String> listNew = list.stream().flatMap(s -> { // 將每個元素轉換成一個stream String[] split = s.split(","); Stream<String> s2 = Arrays.stream(split); return s2; }).collect(Collectors.toList()); System.out.println("處理前的集合:" + list); System.out.println("處理後的集合:" + listNew); } }
輸出結果:
處理前的集合:[m-k-l-a, 1-3-5]
處理後的集合:[m, k, l, a, 1, 3, 5]
3.5 歸約(reduce)
案例一:求Integer
集合的元素之和、乘積和最大值。
public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4); // 求和方式1 Optional<Integer> sum = list.stream().reduce((x, y) -> x + y); // 求和方式2 Optional<Integer> sum2 = list.stream().reduce(Integer::sum); // 求和方式3 Integer sum3 = list.stream().reduce(0, Integer::sum); // 求乘積 Optional<Integer> product = list.stream().reduce((x, y) -> x * y); // 求最大值方式1 Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y); // 求最大值寫法2 Integer max2 = list.stream().reduce(1, Integer::max); System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3); System.out.println("list求積:" + product.get()); System.out.println("list求和:" + max.get() + "," + max2); } }
輸出結果:
list求和:29,29,29 list求積:2112 list求和:11,11
案例二:求所有員工的工資之和和最高工資。
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York")); // 求工資之和方式1: Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum); // 求工資之和方式2: Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2); // 求工資之和方式3: Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum); // 求最高工資方式1: Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), Integer::max); // 求最高工資方式2: Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), (max1, max2) -> max1 > max2 ? max1 : max2); System.out.println("工資之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3); System.out.println("最高工資:" + maxSalary + "," + maxSalary2); } }
輸出結果:
工資之和:49300,49300,49300
最高工資:9500,9500
3.6 收集(collect)
3.6.1 歸集(toList/toSet/toMap)
下面用一個案例演示toList
、toSet
和toMap
:
public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20); List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000) .collect(Collectors.toMap(Person::getName, p -> p)); System.out.println("toList:" + listNew); System.out.println("toSet:" + set); System.out.println("toMap:" + map); } }
執行結果:
toList:[6, 4, 6, 6, 20] toSet:[4, 20, 6] toMap:{Tom=mutest.Person@5fd0d5ae, Anni=mutest.Person@2d98a335}
3.6.2 統計(count/averaging)
Collectors
提供了一系列用於資料統計的靜態方法:
-
計數:
count
-
平均值:
averagingInt
、averagingLong
、averagingDouble
-
最值:
maxBy
、minBy
-
求和:
summingInt
、summingLong
、summingDouble
-
統計以上所有:
summarizingInt
、summarizingLong
、summarizingDouble
案例:統計員工人數、平均工資、工資總額、最高工資。
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); // 求總數 Long count = personList.stream().collect(Collectors.counting()); // 求平均工資 Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary)); // 求最高工資 Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare)); // 求工資之和 Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary)); // 一次性統計所有資訊 DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary)); System.out.println("員工總數:" + count); System.out.println("員工平均工資:" + average); System.out.println("員工工資總和:" + sum); System.out.println("員工工資所有統計:" + collect); } }
執行結果:
員工總數:3 員工平均工資:7900.0 員工工資總和:23700 員工工資所有統計:DoubleSummaryStatistics{count=3, sum=23700.000000,min=7000.000000, average=7900.000000, max=8900.000000}
3.6.3 分組(partitioningBy/groupingBy)
-
分割槽:將
stream
按條件分為兩個Map
,比如員工按薪資是否高於8000分為兩部分。 -
分組:將集合分為多個Map,比如員工按性別分組。有單級分組和多級分組
案例:將員工按薪資是否高於8000分為兩部分;將員工按性別和地區分組
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, "male", "New York")); personList.add(new Person("Jack", 7000, "male", "Washington")); personList.add(new Person("Lily", 7800, "female", "Washington")); personList.add(new Person("Anni", 8200, "female", "New York")); personList.add(new Person("Owen", 9500, "male", "New York")); personList.add(new Person("Alisa", 7900, "female", "New York")); // 將員工按薪資是否高於8000分組 Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000)); // 將員工按性別分組 Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex)); // 將員工先按性別分組,再按地區分組 Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea))); System.out.println("員工按薪資是否大於8000分組情況:" + part); System.out.println("員工按性別分組情況:" + group); System.out.println("員工按性別、地區:" + group2); } }
輸出結果:
員工按薪資是否大於8000分組情況:{false=[mutest.Person@2d98a335, mutest.Person@16b98e56, mutest.Person@7ef20235], true=[mutest.Person@27d6c5e0, mutest.Person@4f3f5b24, mutest.Person@15aeb7ab]} 員工按性別分組情況:{female=[mutest.Person@16b98e56, mutest.Person@4f3f5b24, mutest.Person@7ef20235], male=[mutest.Person@27d6c5e0, mutest.Person@2d98a335, mutest.Person@15aeb7ab]} 員工按性別、地區:{female={New York=[mutest.Person@4f3f5b24, mutest.Person@7ef20235], Washington=[mutest.Person@16b98e56]}, male={New York=[mutest.Person@27d6c5e0, mutest.Person@15aeb7ab], Washington=[mutest.Person@2d98a335]}} 3.6.4 接合(joining)
3.6.4 接合(joining)
joining
可以將stream中的元素用特定的連線符(沒有的話,則直接連線)連線成一個字串。
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(",")); System.out.println("所有員工的姓名:" + names); List<String> list = Arrays.asList("A", "B", "C"); String string = list.stream().collect(Collectors.joining("-")); System.out.println("拼接後的字串:" + string); } }
執行結果:
所有員工的姓名:Tom,Jack,Lily
拼接後的字串:A-B-C
3.6.5 歸約(reducing)
Collectors
類提供的reducing
方法,相比於stream
本身的reduce
方法,增加了對自定義歸約的支援。
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); // 每個員工減去起徵點後的薪資之和(這個例子並不嚴謹,但一時沒想到好的例子) Integer sum = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000))); System.out.println("員工扣稅薪資總和:" + sum); // stream的reduce Optional<Integer> sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum); System.out.println("員工薪資總和:" + sum2.get()); } }
執行結果:
員工扣稅薪資總和:8700
員工薪資總和:23700
3.7 排序(sorted)
sorted,中間操作。有兩種排序:
-
sorted():自然排序,流中元素需實現Comparable介面
-
sorted(Comparator com):Comparator排序器自定義排序
案例:將員工按工資由高到低(工資一樣則按年齡由大到小)排序
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Sherry", 9000, 24, "female", "New York")); personList.add(new Person("Tom", 8900, 22, "male", "Washington")); personList.add(new Person("Jack", 9000, 25, "male", "Washington")); personList.add(new Person("Lily", 8800, 26, "male", "New York")); personList.add(new Person("Alisa", 9000, 26, "female", "New York")); // 按工資增序排序 List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName) .collect(Collectors.toList()); // 按工資倒序排序 List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()) .map(Person::getName).collect(Collectors.toList()); // 先按工資再按年齡自然排序(從小到大) List<String> newList3 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()) .map(Person::getName).collect(Collectors.toList()); // 先按工資再按年齡自定義排序(從大到小) List<String> newList4 = personList.stream().sorted((p1, p2) -> { if (p1.getSalary() == p2.getSalary()) { return p2.getAge() - p1.getAge(); } else { return p2.getSalary() - p1.getSalary(); } }).map(Person::getName).collect(Collectors.toList()); System.out.println("按工資自然排序:" + newList); System.out.println("按工資降序排序:" + newList2); System.out.println("先按工資再按年齡自然排序:" + newList3); System.out.println("先按工資再按年齡自定義降序排序:" + newList4); } }
執行結果:
按工資自然排序:[Lily, Tom, Sherry, Jack, Alisa]
按工資降序排序:[Sherry, Jack, Alisa,Tom, Lily]
先按工資再按年齡自然排序:[Sherry, Jack, Alisa, Tom, Lily]
先按工資再按年齡自定義降序排序:[Alisa, Jack, Sherry, Tom, Lily]
3.8 提取/組合
public class StreamTest { public static void main(String[] args) { String[] arr1 = { "a", "b", "c", "d" }; String[] arr2 = { "d", "e", "f", "g" }; Stream<String> stream1 = Stream.of(arr1); Stream<String> stream2 = Stream.of(arr2); // concat:合併兩個流 distinct:去重 List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()); // limit:限制從流中獲得前n個數據 List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList()); // skip:跳過前n個數據 List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList()); System.out.println("流合併:" + newList); System.out.println("limit:" + collect); System.out.println("skip:" + collect2); } }
執行結果:
流合併:[a, b, c, d, e, f, g] limit:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19] skip:[3, 5, 7, 9, 11]