Java Stream的基本用法
項目遇到一個需求,需要對集合 List 進行遍歷、篩選,按照傳統的寫法,就是直接 for 循環進行條件判斷,這樣的做法很是啰嗦麻煩,Java8 Stream 流操作能夠簡潔地解決這個問題。網上對於 Stream 的介紹及相關用法很詳細,這里列舉簡單的用法。
博客參考文章1:https://blog.csdn.net/y_k_y/article/details/84633001
博客參考文章2:https://blog.csdn.net/mu_wind/article/details/109516995
1、Stream介紹
Stream 是 Java 8 的新特性之一,它能夠將數組、集合轉換成流,借助Stream API 對流中的元素進行操作,比如篩選、排序、聚合等。這種對流中數據的操作,類似於使用SQL執行的數據庫查詢。
Stream 有下面幾個特性:
- stream不存儲數據,而是按照特定的規則對數據進行計算,一般會輸出結果。
- stream不會改變數據源,通常情況下會產生一個新的集合或一個值。
- stream具有延遲執行特性,只有調用終端操作時,中間操作才會執行。
2、Stream操作分類
Stream可以由數組或集合創建,對流的操作分為兩種:
- 中間操作:每次返回一個新的流,可以有多個。
- 終端操作:每個流只能進行一次終端操作,終端操作結束后流無法再次使用。終端操作會產生一個新的集合或值。
3、Stream 創建
Stream可以由數組、集合創建
3.1、通過 java.util.Collection.stream()
方法用集合創建流
List<String> list = Arrays.asList("hello","world","stream");
//創建順序流
Stream<String> stream = list.stream();
//創建並行流
Stream<String> parallelStream = list.parallelStream();
3.2、使用java.util.Arrays.stream(T[] array)
方法用數組創建流
String[] array = {"h", "e", "l", "l", "o"};
Stream<String> arrayStream = Arrays.stream(array);
3.3、使用Stream
的靜態方法:of()、iterate()、generate()
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 2).limit(3);
stream2.forEach(System.out::println);
Stream<Double> stream3 = Stream.generate(Math::random).limit(3);
stream3.forEach(System.out::println)
輸出結果如下:
0
2
4
0.9620319103852426
0.8303672905658537
0.09203215202737569
3.4、stream
和parallelStream
的簡單區分
stream
是順序流,由主線程按順序對流執行操作,而parallelStream
是並行流,內部以多線程並行執行的方式對流進行操作,但前提是流中的數據處理沒有順序要求。例如篩選集合中的奇數,兩者的處理不同之處:
如果流中的數據量足夠大,並行流可以加快處速度。
除了直接創建並行流,還可以通過parallel()
把順序流轉換成並行流:
Optional<Integer> findFirst = list.stream().parallel().filter(x->x>4).findFirst();
4、Stream 使用
4.1 遍歷/匹配(foreach/find/match)
Stream
也是支持類似集合的遍歷和匹配元素的,只是Stream
中的元素是以Optional
類型存在的。Stream
的遍歷、匹配非常簡單。
Optional
類是一個可以為null
的容器對象。如果值存在則isPresent()
方法會返回true
,調用get()
方法會返回該對象。后面會出關於'Optional
類的博客。
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);
}
4.2 篩選(filter)
篩選,是按照一定的規則校驗流中的元素,將符合條件的元素提取到新的流中的操作。
篩選出集合中大於5的元素,並打印出來。
public static void main(String[] args) {
List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2);
Stream<Integer> stream = list.stream();
stream.filter(x -> x > 5).forEach(System.out::println);
}
結果如下:
6
7
8
4.3 聚合(max/min/count)
max
、min
、count
這些字眼你一定不陌生,沒錯,在mysql中我們常用它們進行數據統計。Java stream中也引入了這些概念和用法,極大地方便了我們對集合、數組的數據統計工作。
獲取String
集合中最長的元素。
public static void main(String[] args) {
List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "helloStream");
Optional<String> max = list.stream().max(Comparator.comparing(String::length));
System.out.println("最長的字符串:" + max.get());
}
結果如下:
最長的字符串:helloStream
4.4 映射(map/flatMap)
映射,可以將一個流的元素按照一定的映射規則映射到另一個流中。分為map
和flatMap
:
map
:接收一個函數作為參數,該函數會被應用到每個元素上,並將其映射成一個新的元素。flatMap
:接收一個函數作為參數,將流中的每個值都換成另一個流,然后把所有流連接成一個流。
map:英文字符串數組的元素全部改為大寫。整數數組每個元素+3。
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]
flatMap: 將兩個字符數組合並成一個新的字符數組。
public static void main(String[] args) {
List<String> list1 = Arrays.asList("m,k,l,a", "1,3,5,7");
List<String> listNew = list1.stream().flatMap(s -> {
// 將每個元素轉換成一個stream
String[] split = s.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());
System.out.println("處理前的集合:" + list1);
System.out.println("處理后的集合:" + listNew);
}
結果如下:
處理前的集合:[m,k,l,a, 1,3,5,7]
處理后的集合:[m, k, l, a, 1, 3, 5, 7]
4.5 歸約(reduce)
歸約,也稱縮減,顧名思義,是把一個流縮減成一個值,能實現對集合求和、求乘積和求最值操作。
求Integer
集合的元素之和、乘積和最大值
public static void main(String[] args) {
List<Integer> list2 = Arrays.asList(1, 3, 2, 8, 11, 4);
// 求和方式1
Optional<Integer> sum = list2.stream().reduce((x, y) -> x + y);
// 求和方式2
Optional<Integer> sum2 = list2.stream().reduce(Integer::sum);
// 求和方式3
Integer sum3 = list2.stream().reduce(0, Integer::sum);
// 求乘積
Optional<Integer> product = list2.stream().reduce((x, y) -> x * y);
// 求最大值方式1
Optional<Integer> max = list2.stream().reduce((x, y) -> x > y ? x : y);
// 求最大值寫法2
Integer max2 = list2.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);
}
4.6 收集(collect)
collect
,收集,可以說是內容最繁多、功能最豐富的部分了。從字面上去理解,就是把一個流收集起來,最終可以是收集成一個值也可以收集成一個新的集合。
collect
主要依賴java.util.stream.Collectors
類內置的靜態方法。
4.6.1 歸集(toList/toSet/toMap)
因為流不存儲數據,那么在流中的數據完成處理后,需要將流中的數據重新歸集到新的集合里。toList
、toSet
和toMap
比較常用,另外還有toCollection
、toConcurrentMap
等復雜一些的用法。
演示toList
、toSet
和toMap
User 實體類
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(value="User對象", description="")
public class User implements Serializable {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主鍵ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "姓名")
private String name;
@ApiModelProperty(value = "年齡")
private Integer age;
@ApiModelProperty(value = "郵箱")
private String email;
}
案例演示toList
、toSet
和toMap
public static void main(String[] args) {
List<Integer> list3 = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
List<Integer> listNew3 = list3.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
Set<Integer> set = list3.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "tony", 12, "202@qq.com"));
userList.add(new User(2L, "hai", 15, "372@qq.com"));
userList.add(new User(3L, "summer", 20, "865@163.com"));
Map<?, User> map = userList.stream().filter(p -> p.getAge() > 14)
.collect(Collectors.toMap(User::getName, p -> p));
System.out.println("toList:" + listNew3);
System.out.println("toSet:" + set);
System.out.println("toMap:" + map);
}
結果如下:
toList:[6, 4, 6, 6, 20]
toSet:[4, 20, 6]
toMap:{hai=User(id=2, name=hai, age=15, email=372@qq.com), summer=User(id=3, name=summer, age=20, email=865@163.com)}
4.6.2 統計(count/averaging)
Collectors
提供了一系列用於數據統計的靜態方法:
- 計數:
count
- 平均值:
averagingInt
、averagingLong
、averagingDouble
- 最值:
maxBy
、minBy
- 求和:
summingInt
、summingLong
、summingDouble
- 統計以上所有:
summarizingInt
、summarizingLong
、summarizingDouble
統計用戶數、平均年齡、年齡總數、最大年齡。
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "tony", 12, "202@qq.com"));
userList.add(new User(2L, "hai", 15, "372@qq.com"));
userList.add(new User(3L, "summer", 20, "865@163.com"));
// 求用戶數
Long count = userList.stream().collect(Collectors.counting());
// 求平均年齡
Double average = userList.stream().collect(Collectors.averagingDouble(User::getAge));
// 求最大年齡
Optional<Integer> max1 = userList.stream().map(User::getAge).collect(Collectors.maxBy(Integer::compare));
// 求年齡總數
Integer sum1 = userList.stream().collect(Collectors.summingInt(User::getAge));
// 一次性統計所有信息
IntSummaryStatistics collect = userList.stream().collect(Collectors.summarizingInt(User::getAge));
System.out.println("用戶總數:" + count);
System.out.println("用戶平均年齡:" + average);
System.out.println("用戶年齡總和:" + sum1);
System.out.println("用戶年齡所有統計:" + collect);
}
結果如下:
用戶總數:3
用戶平均年齡:15.666666666666666
用戶年齡總和:47
用戶年齡所有統計:IntSummaryStatistics{count=3, sum=47, min=12, average=15.666667, max=20}
4.6.3 分組(partitioningBy/groupingBy)
- 分區:將
stream
按條件分為兩個Map
,比如用戶按年齡是否高於14分為兩部分。 - 分組:將集合分為多個Map,比如用戶按郵箱類型分組。有單級分組和多級分組。
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "tony", 12, "202@qq.com"));
userList.add(new User(2L, "hai", 15, "372@qq.com"));
userList.add(new User(3L, "summer", 20, "865@163.com"));
// 用戶按年齡是否高於14分組
Map<Boolean, List<User>> part = userList.stream().collect(Collectors.partitioningBy(User -> User.getAge() > 8000));
// 用戶按郵箱類型分組分組
Map<Boolean, List<User>> group = userList.stream().collect(Collectors.groupingBy(User -> User.getEmail().contains("qq.com")));
System.out.println("用戶按年齡是否高於14分組:" + part);
System.out.println("用戶按郵箱類型分組分組:" + group);
}
結果如下
用戶按年齡是否高於14分組:{false=[User(id=1, name=tony, age=12, email=202@qq.com), User(id=2, name=hai, age=15, email=372@qq.com), User(id=3, name=summer, age=20, email=865@163.com)], true=[]}
用戶按郵箱類型分組分組:{false=[User(id=3, name=summer, age=20, email=865@163.com)], true=[User(id=1, name=tony, age=12, email=202@qq.com), User(id=2, name=hai, age=15, email=372@qq.com)]}
4.6.4 接合(joining)
joining
可以將stream中的元素用特定的連接符(沒有的話,則直接連接)連接成一個字符串。
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "tony", 12, "202@qq.com"));
userList.add(new User(2L, "hai", 15, "372@qq.com"));
userList.add(new User(3L, "summer", 20, "865@163.com"));
String names = userList.stream().map(user -> user.getName()).collect(Collectors.joining(","));
System.out.println("所有用戶的姓名:" + names);
}
結果如下
所有用戶的姓名:tony,hai,summer
4.6.5 歸約(reducing)
Collectors
類提供的reducing
方法,相比於stream
本身的reduce
方法,增加了對自定義歸約的支持。
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "tony", 12, "202@qq.com"));
userList.add(new User(2L, "hai", 15, "372@qq.com"));
userList.add(new User(3L, "summer", 20, "865@163.com"));
// 每個用戶年齡數加0減去2
Integer sum4 = userList.stream().collect(Collectors.reducing(0, User::getAge, (i, j) -> (i + j - 2)));
System.out.println("用戶剩余年齡總和:" + sum4);
}
4.7 排序(sorted)
sorted,中間操作。有兩種排序:
- sorted():自然排序,流中元素需實現Comparable接口
- sorted(Comparator com):Comparator排序器自定義排序
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "tony", 12, "202@qq.com"));
userList.add(new User(2L, "hai", 15, "372@qq.com"));
userList.add(new User(3L, "summer", 20, "865@163.com"));
// 按用戶年齡降序排序
List<String> newList2 = userList.stream().sorted(Comparator.comparing(User::getAge).reversed())
.map(User::getName).collect(Collectors.toList());
System.out.println("按工資降序排序:" + newList2);
}
4.8 提取/組合
流也可以進行合並、去重、限制、跳過等操作。
public static void main(String[] args) {
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
Stream<String> streamExample1 = Stream.of(arr1);
Stream<String> streamExample2 = Stream.of(arr2);
// concat:合並兩個流 distinct:去重
List<String> newList = Stream.concat(streamExample1, streamExample2).distinct().collect(Collectors.toList());
// limit:限制從流中獲得前n個數據
List<Integer> collect1 = 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:" + collect1);
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]
至此,基本用法演示完畢,后續使用到新的用法,將會持續更新。