Interface Stream
Stream: A sequence of elements supporting sequential and parallel aggregate operations.
1 | int sum = widgets.stream() |
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 | collect() |
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
4Stream<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
4Stream<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 | import java.util.ArrayList; |