The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
Java8 Stream API 详细使用指南

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.

file

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 sourcestrArrSet length to see if it has changed. The result was removed from the streamjavaThis element, butstrArrBut nothing has changed.

file

Next we start to sort out how to create streams.

2.1 empty flow

file

You should have noticed that in the picture above, I useCollections Created an emptyListThe 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

file

Excerpts from the Java 8 Collection above describe as long asCollection<E>can create streams.

file

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

file

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.

file

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

file

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.

file

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:IntStreamLongStreamDoubleStream

Using these new APIs improves productivity by avoiding unnecessary automatic boxing:

file

Both methods start at 1 and create sequences with steps of 1. difference isendExclusive=3
rangeMethod does not contain 3, butrangeClosedIncluding 3.

Starting with Java 8,RandomClasses provide a wide range of methods for generating basic type streams. For example, the following code creates aDoubleStream, it has three randomdoubleElements:

file

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 JDKIntStreamUsed to represent character stream substitution.

file

The following example is based on the specifiedRegExwillStringSplit into substrings:

file

2.8 file stream

Java NIO classesFilesallowed to pass throughlines()Method to generate text filesStream <String>。Each line of text becomes an element of the flow:

file

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.synchronizedseries. Or when a parallel stream collects elements into a collection, callcollectMethod, you must not use itForeachmethod ormapmethod.

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:

file

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:

file

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

file

file

file

file
file
file

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.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/3136.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

完整版APP区块链游戏源码,trx投注竞猜游戏,trx下注游戏,前端uinapp
Full version of APP blockchain game source code, trx betting game, trx betting game, front-end uinapp
Someone bought it 8 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish