Interface Stream

Interface Stream

Stream: A sequence of elements supporting sequential and parallel aggregate operations.

1
2
3
4
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();

In this example, widgets is a Collection<Widget>. We create a stream of Widget objects via Collection.stream(), filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Then this stream is summed to produce a total weight.


Aggregate methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
collect()

concat()

count()

distinct()

filter()

flatMap()

forEach()

...

flatMap: ~ unzip in python:

1
2
3
{ {1,2}, {3,4}, {5,6} } -> flatMap -> {1,2,3,4,5,6}

{ {'a','b'}, {'c','d'}, {'e','f'} } -> flatMap -> {'a','b','c','d','e','f'}

In Java 8, Stream can hold different data types, for examples:

1
2
3
4
Stream<String[]>	
Stream<Set<String>>
Stream<List<String>>
Stream<List<Object>>

But, the Stream operations (filter, sum, distinct…) and collectors do not support it, so, we need flatMap() to do the following conversion :

1
2
3
4
Stream<String[]>		-> flatMap ->	Stream<String>
Stream<Set<String>> -> flatMap -> Stream<String>
Stream<List<String>> -> flatMap -> Stream<String>
Stream<List<Object>> -> flatMap -> Stream<Object>


parallelStream():

Collection.stream() creates a sequential stream, and Collection.parallelStream() creates a parallel one.

也就是说, .stream().parallelStream()都是collections的方法: Collection.parallelStream()

e.g. print a to z:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.ArrayList;
import java.util.List;

public class ParallelExample2 {

public static void main(String[] args) {

System.out.println("Normal...");

List<String> alpha = getData();
alpha.stream().forEach(System.out::println);

System.out.println("Parallel...");

List<String> alpha2 = getData();
alpha2.parallelStream().forEach(System.out::println);

}

private static List<String> getData() {

List<String> alpha = new ArrayList<>();

int n = 97; // 97 = a , 122 = z
while (n <= 122) {
char c = (char) n;
alpha.add(String.valueOf(c));
n++;
}

return alpha;

}

}