
1. overview
An important feature introduced by Java 8 is undoubtedly the Stream API. Stream translates as "stream". It suddenly occurred to me that big data processing has the concept of streaming computing. Data is filtered and aggregated through pipelines and passed through handlers. Moreover, the streams are all vector-oriented, emphasizing the computational processing of data, while collections emphasize data sets. A Stream can be seen as an operable sequence of datasets that can specify the operations you want to do on the collection and perform very complex operations such as finding, filtering, and mapping data. It's a bit similar to adding, deleting and revising operations in a database. Very efficient and easy to use.
2. Create a Stream
There are many ways to create streams from different data sources. The stream that is created does not change the data source. What does it mean? For example, after creating a stream from a collection, the operation of the stream does not change the data state of the collection. Let's give an example.
As shown in the figure above, we put a collection of length 3 into a stream, filter out elements whose element length is no more than 4, and then iterate over the rest. At the same time, we also printed the original data sourcestrArr
Set length to see if it has changed. The result was removed from the streamjava
This element, butstrArr
But nothing has changed.
Next we start to sort out how to create streams.
2.1 empty flow
You should have noticed that in the picture above, I useCollections
Created an emptyList
The same is true for flow, and the meaning of the two is the same. All are to avoid returning because there are no elementsnull
。
2.2 Create a stream from a collection
Excerpts from the Java 8 Collection above describe as long asCollection<E>
can create streams.
2.3 Create a stream from an array
We can create a stream from an array, or we can create a stream by intercepting a portion of the array based on the index
2.4 Create a stream through a constructor
Stream provides builder methods to build streams. However, pay attention to generic constraints, otherwise a stream of type Object will be returned.
2.5 infinite element
generate()
method receives Supplier<T>
Function to generate elements, and generation will not stop until memory limits are imposed. The following example will generate a character stream with a length of 10 and a string element length of 5
Another way to create unlimited streams is to use theiterate()
method. andgenerate()
The same methods must be limited. the difference is
The first parameter of the iterate() method serves as the starting seed, and the second function parameter customizes the rules for generating elements. the following example
It starts from 1 as the first element, and each element is incremented by 1 based on the previous element, and the length is limited to 10. 1-10 will be printed below.
2.6 basic type flow
Java 8 provides the possibility to create streams from three basic types: int, long, and double. Because Stream is a general interface and cannot use basic types as type parameters for generics, three new special interfaces have been created:IntStream
,LongStream
,DoubleStream
。
Using these new APIs improves productivity by avoiding unnecessary automatic boxing:
Both methods start at 1 and create sequences with steps of 1. difference isendExclusive=3
range
Method does not contain 3, butrangeClosed
Including 3.
Starting with Java 8,Random
Classes provide a wide range of methods for generating basic type streams. For example, the following code creates aDoubleStream
, it has three randomdouble
Elements:
2.7 character stream
String can also be used as a source for creating streams.
With the help of String classchars()
method. because there is noCharStream
, in JDKIntStream
Used to represent character stream substitution.
The following example is based on the specifiedRegEx
willString
Split into substrings:
2.8 file stream
Java NIO classesFiles
allowed to pass throughlines()
Method to generate text filesStream <String>
。Each line of text becomes an element of the flow:
you can alsolines()
Method specifies the character set encoding in the.
2.9 parallel streams
Parallel flow is a flow that divides a content into multiple data blocks, divides it into multiple data blocks with different threads, and processes each data block separately with different threads. The bottom layer uses the Fork/Join framework. This stream is mainly used to process large batches of data sources. Small amounts of data are not recommended. Declaration methods with parallel are all parallel streams and will not be introduced here.
However, when using it, you must pay attention to data parallel processing and synchronization. or use synchronized collections such asCollections.synchronized
series. Or when a parallel stream collects elements into a collection, callcollect
Method, you must not use itForeach
method ormap
method.
3. References to streams
You can instantiate a stream and have accessible references to it as long as you call only intermediate operations. Performing terminal actions makes the stream inaccessible. Technically, the following code seems to work:
Line 3 is the terminal operation. If line 4 is followed to reuse the stream, it will be triggeredIllegalStateException
。Be sure to keep in mind that the same Stream in Java 8 cannot be reused after terminal operations. The correct way to do this is as follows:
4. Intermediate operations of flow
Intermediate operations are calculation operations on data in the data source. In fact, we have already performed many intermediate operations on convection above, such asfilter()
、limit()
Wait.
Some well-known intermediate operation explanations on the Internet
5. Life cycle of flow
Create Stream as a data source (e.g., collection, array) and get a stream
Intermediate operation A chain of intermediate operations that process data from the data source
Termination operation (terminal operation) A termination operation that executes an intermediate chain of operations and produces results, so that the entire stream dies out.
6. summary
Java 8 Stream is a milestone. Changing the previous model of data processing. Through this article, the convection and the life cycle of the flow are described in detail. I believe you can already improve your development efficiency through Stream.
Comments0