- Java8中的Stream使用
-
- 1. 概述
- 2. 分類
- 3. 具體用法
-
- 3.1 流的常用建立方法
-
- 3.1.1 使用 Collection下的 `stream()` 和 `parallelStream()` 方法
- 3.1.2 使用 Arrays 中的 `stream()` 方法,将數組轉成流
- 3.1.3 使用 Stream 中的靜态方法:`of()`、`iterate()`、`generate()`
- 3.1.4 使用 `BufferedReader.lines()` 方法,将每行内容轉成流
- 3.1.5 使用 `Pattern.splitAsStream()` 方法,将字元串分隔成流
- 3.2 流的中間操作
-
- 3.2.1 篩選與切片
- 3.2.2 映射
- 3.2.3 排序
- 3.2.4 消費
- 3.3 流的終止操作
-
- 3.3.1 比對、聚合操作
- 3.3.2 規約操作
- 3.3.3 收集操作
-
- 3.3.3.1 Collector 工具庫:Collectors
- 3.3.3.2 Collectors.toList() 解析
- Reference
Java8中的Stream使用
1. 概述
Stream
是 Java8 中處理集合的關鍵抽象概念,它可以指定你希望對集合進行的操作,可以執行非常複雜的查找、過濾和映射資料等操作。使用Stream API 對集合資料進行操作,就類似于使用 SQL 執行的資料庫查詢。也可以使用 Stream API 來并行執行操作。簡而言之,Stream API 提供了一種高效且易于使用的處理資料的方式。
特點:
1 . 不是資料結構,不會儲存資料。
2 . 不會修改原來的資料源,它會将操作後的資料儲存到另外一個對象中。(保留意見:畢竟peek方法可以修改流中元素)
3 . 惰性求值,流在中間處理過程中,隻是對操作進行了記錄,并不會立即執行,需要等到執行終止操作的時候才會進行實際的計算。
2. 分類
-
:指元素的處理不受之前元素的影響無狀态
-
:指該操作隻有拿到所有元素之後才能繼續下去有狀态
-
:指必須處理所有元素才能得到最終結果非短路操作
-
:指遇到某些符合條件的元素就可以得到最終結果,如 A || B,隻要A為true,則無需判斷B的結果。短路操作
3. 具體用法
3.1 流的常用建立方法
3.1.1 使用 Collection下的 stream()
和 parallelStream()
方法
stream()
parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream(); //擷取一個順序流
Stream<String> parallelStream = list.parallelStream(); //擷取一個并行流
3.1.2 使用 Arrays 中的 stream()
方法,将數組轉成流
stream()
Integer[] nums = new Integer[10];
Stream<Integer> stream = Arrays.stream(nums);
3.1.3 使用 Stream 中的靜态方法: of()
、 iterate()
、 generate()
of()
iterate()
generate()
Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 2).limit(6);
stream2.forEach(System.out::println); // 0 2 4 6 8 10
Stream<Double> stream3 = Stream.generate(Math::random).limit(2);
stream3.forEach(System.out::println);
3.1.4 使用 BufferedReader.lines()
方法,将每行内容轉成流
BufferedReader.lines()
BufferedReader reader = new BufferedReader(new FileReader("F:\test_stream.txt"));
Stream<String> lineStream = reader.lines();
lineStream.forEach(System.out::println);
3.1.5 使用 Pattern.splitAsStream()
方法,将字元串分隔成流
Pattern.splitAsStream()
Pattern pattern = Pattern.compile(",");
Stream<String> stringStream = pattern.splitAsStream("a,b,c,d");
stringStream.forEach(System.out::println);
3.2 流的中間操作
3.2.1 篩選與切片
-
:過濾流中的某些元素filter
-
:擷取n個元素limit(n)
-
:跳過n元素,配合 limit(n) 可實作分頁skip(n)
-
:通過流中元素的 hashCode() 和 equals() 去除重複元素distinct
Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
Stream<Integer> newStream = stream.filter(s -> s > 5) // 6 6 7 9 8 10 12 14 14
.distinct() // 6 7 9 8 10 12 14
.skip(2) // 9 8 10 12 14
.limit(2); // 9 8
newStream.forEach(System.out::println);
3.2.2 映射
-
:接收一個函數作為參數,該函數會被應用到每個元素上,并将其映射成一個新的元素。map
-
:接收一個函數作為參數,将流中的每個值都換成另一個流,然後把所有流連接配接成一個流。flatMap
List<String> list = Arrays.asList("a,b,c", "1,2,3");
//将每個元素轉成一個新的且不帶逗号的元素
Stream<String> s1 = list.stream().map(s -> s.replaceAll(",", ""));
s1.forEach(System.out::println); // abc 123
Stream<String> s3 = list.stream().flatMap(s -> {
//将每個元素轉換成一個stream
String[] split = s.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
});
s3.forEach(System.out::println); // a b c 1 2 3
3.2.3 排序
-
:自然排序,流中元素需實作Comparable接口sorted()
-
:定制排序,自定義Comparator排序器sorted(Comparator com)
List<String> list = Arrays.asList("aa", "ff", "dd");
//String 類自身已實作Compareable接口
list.stream().sorted().forEach(System.out::println); // aa dd ff
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
Student s3 = new Student("aa", 30);
Student s4 = new Student("dd", 40);
List<Student> studentList = Arrays.asList(s1, s2, s3, s4);
// 自定義排序:先按姓名升序,姓名相同則按年齡升序
studentList.stream().sorted(
(o1, o2) -> {
if (o1.getName().equals(o2.getName())) {
return o1.getAge() - o2.getAge();
} else {
return o1.getName().compareTo(o2.getName());
}
}
).forEach(System.out::println);
3.2.4 消費
-
:如同于map,能得到流中的每一個元素。但map接收的是一個Function表達式,有傳回值;而peek接收的是Consumer表達式,沒有傳回值。peek()
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);
studentList.stream()
.peek(o -> o.setAge(100))
.forEach(System.out::println);
// 結果:
Student{name='aa', age=100}
Student{name='bb', age=100}
3.3 流的終止操作
3.3.1 比對、聚合操作
-
:接收一個 Predicate 函數,隻要流中有一個元素滿足該斷言則傳回true,否則傳回falseanyMatch
-
:接收一個 Predicate 函數,當流中每個元素都符合該斷言時才傳回true,否則傳回falseallMatch
-
:接收一個 Predicate 函數,當流中每個元素都不符合該斷言時才傳回true,否則傳回falsenoneMatch
-
:傳回流中第一個元素findFirst
-
:傳回流中的任意元素findAny
-
:傳回流中元素的總個數count
-
:傳回流中元素最大值max
-
:傳回流中元素最小值min
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
boolean allMatch = list.stream().allMatch(e -> e > 10); // false
boolean noneMatch = list.stream().noneMatch(e -> e > 10); // true
boolean anyMatch = list.stream().anyMatch(e -> e > 4); // true
Integer findFirst = list.stream().findFirst().get(); // 1
Integer findAny = list.stream().findAny().get(); // 1
long count = list.stream().count(); // 5
Integer max = list.stream().max(Integer::compareTo).get(); // 5
Integer min = list.stream().min(Integer::compareTo).get(); // 1
3.3.2 規約操作
-
:第一次執行時,accumulator函數的第一個參數為流中的第一個元素,第二個參數為流中元素的第二個元素;第二次執行時,第一個參數為第一次函數執行的結果,第二個參數為流中的第三個元素;依次類推。Optional<T> reduce(BinaryOperator<T> accumulator)
-
:流程跟上面一樣,隻是第一次執行時,accumulator函數的第一個參數為identity,而第二個參數為流中的第一個元素。T reduce(T identity, BinaryOperator<T> accumulator)
-
:在串行流(stream)中,該方法跟第二個方法一樣,即第三個參數combiner不會起作用。在并行流(parallelStream)中,我們知道流被fork join出多個線程進行執行,此時每個線程的執行流程就跟第二個方法 reduce(identity,accumulator) 一樣,而第三個參數combiner函數,則是将每個線程的執行結果當成一個新的流,然後使用第一個方法 reduce(accumulator) 流程進行規約。<U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner)
// 經過測試,當元素個數小于24時,并行時線程數等于元素個數,當大于等于24時,并行時線程數為16
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);
Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();
System.out.println(v); // 300
Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2);
System.out.println(v1); //310
Integer v2 = list.stream().reduce(0,
(x1, x2) -> {
System.out.println("stream accumulator: x1:" + x1 + " x2:" + x2);
return x1 - x2;
},
(x1, x2) -> {
System.out.println("stream combiner: x1:" + x1 + " x2:" + x2);
return x1 * x2;
});
System.out.println(v2); // -300
Integer v3 = list.parallelStream().reduce(0,
(x1, x2) -> {
System.out.println("parallelStream accumulator: x1:" + x1 + " x2:" + x2);
return x1 - x2;
},
(x1, x2) -> {
System.out.println("parallelStream combiner: x1:" + x1 + " x2:" + x2);
return x1 * x2;
});
System.out.println(v3); //197474048
3.3.3 收集操作
-
:接收一個Collector執行個體,将流中元素收內建另外一個資料結構。collect
-
是一個接口,有以下5個抽象方法:Collector<T, A, R>
-
:建立一個結果容器ASupplier<A> supplier()
-
:消費型接口,第一個參數為容器A,第二個參數為流中元素T。BiConsumer<A, T> accumulator()
-
:函數接口,該參數的作用跟上一個方法(reduce)中的combiner參數一樣,将并行流中各 個子程序的運作結果(accumulator函數操作後的容器A)進行合并。BinaryOperator<A> combiner()
-
:函數式接口,參數為:容器A,傳回類型為:collect方法最終想要的結果R。Function<A, R> finisher()
-
:傳回一個不可變的Set集合,用來表明該Collector的特征。有以下三個特征:Set<Characteristics> characteristics()
- CONCURRENT:表示此收集器支援并發。(官方文檔還有其他描述,暫時沒去探索,故不作過多翻譯)
- UNORDERED:表示該收集操作不會保留流中元素原有的順序。
- IDENTITY_FINISH:表示finisher參數隻是辨別而已,可忽略。
-
注:如果對以上函數接口不太了解的話,可參考我另外一篇文章:Java 8 函數式接口
3.3.3.1 Collector 工具庫:Collectors
Student s1 = new Student("aa", 10, 1);
Student s2 = new Student("bb", 20, 2);
Student s3 = new Student("cc", 10, 3);
List<Student> list = Arrays.asList(s1, s2, s3);
// 裝成list
List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList()); // [10, 20, 10]
// 轉成set
Set<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]
// 轉成map, 注:key不能相同,否則報錯
Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge)); // {cc=10, bb=20, aa=10}
// 字元串分隔符連接配接
String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)
// 聚合操作
// 1.學生總數
Long count = list.stream().collect(Collectors.counting()); // 3
// 2.最大年齡 (最小的minBy同理)
Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get(); // 20
// 3.所有人的年齡
Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge)); // 40
// 4.平均年齡
Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge)); // 13.333333333333334
// 帶上以上所有方法
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
// 分組
Map<Integer, List<Student>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
// 多重分組,先根據類型分再根據年齡分
Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));
// 分區
// 分成兩部分,一部分大于10歲,一部分小于等于10歲
Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
// 規約
Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40
3.3.3.2 Collectors.toList() 解析
// toList 源碼
public static <T> Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
(left, right) -> {
left.addAll(right);
return left;
}, CH_ID);
}
//為了更好地了解,我們轉化一下源碼中的lambda表達式
public <T> Collector<T, ?, List<T>> toList() {
Supplier<List<T>> supplier = () -> new ArrayList();
BiConsumer<List<T>, T> accumulator = (list, t) -> list.add(t);
BinaryOperator<List<T>> combiner = (list1, list2) -> {
list1.addAll(list2);
return list1;
};
Function<List<T>, List<T>> finisher = (list) -> list;
Set<Collector.Characteristics> characteristics = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
return new Collector<T, List<T>, List<T>>() {
@Override
public Supplier supplier() {
return supplier;
}
@Override
public BiConsumer accumulator() {
return accumulator;
}
@Override
public BinaryOperator combiner() {
return combiner;
}
@Override
public Function finisher() {
return finisher;
}
@Override
public Set<Characteristics> characteristics() {
return characteristics;
}
};
}
Reference
- Java8 Stream的詳細用法