Java 8’s stream API uses

preface

This time I want to introduce the API use of Java stream. I'm working on a new project recently, and then I can finally jump out of the ancestral code pit of the old project. After the project is built with the company's own framework, I wanted to upgrade the JDK version as well (for previous projects, JDK7 can be used at most), but later I found that the company's project deployment and packaging platform only supports jdk8 at most. Well, since jdk8 is supported, it can also meet daily needs After upgrading to jdk8, I started to write some basic logic after building the project architecture. Some jdk8 streams were used. But my colleagues said they couldn't understand my code. Indeed, I also admit that although the code of lambda expression is concise, people who can't use it will think its readability is not very good. So this time Let's introduce some functions of Java stream based on our own experience.

From traversal to stream operation

Oracle released Java 8 on March 18, 2014. Java 8 mainly adds the ability of functional programming on the basis of the original object-oriented. In this way, lambda expressions are used in Java to pass a function as a method parameter. Java 8 stream is a typical example. The stream API can greatly improve the productivity of Java programmers and enable programmers to write efficient, clean and concise code.

example:

The code traversed above is converted to stream API to achieve the following:

Normal traversal can be realized with one line of stream.

The following is a flow chart implemented using the stream API.

Converting to Java code is

Create stream

Arrays. stream()

When facing an array in daily programming, you can also use arrays Stream () method to use stream

Stream. of()

When facing an array, you can use arrays In addition to the stream () method, you can also use stream to convert the required array into stream. This method supports not only passing in an array and converting the array into a stream, but also passing in multiple parameters and finally converting the parameters into a stream

Actually, stream Of () is also the called stream Of () method.

Stream. generate()

The stream interface has two static methods for creating an infinite stream. The generate () method accepts a parameter function. You can use code similar to the following to create a stream you need.

Operation results

Stream. iterate()

Another static method of the stream interface for creating an infinite stream is the iterate () method. The iterate () method also accepts a parameter function. You can use code similar to the following to create a stream you need.

Operation results

Collection. stream()

This is the most common stream. Because collection is the parent interface of the collection interface in Java, all collections in Java inherit or implement this interface. Therefore, collections in Java can use this method to create a stream;

example

StreamSupport. stream()

By viewing the collection We can see the method of stream (), colleciton Stream() actually called streamsupport Stream(). So we can also use streamsupport Stream() to create a stream. When we are facing an iterator, we use streamsupport Stream () can create a stream. The first parameter is to pass in an iterator, and the second parameter is true, which means to use parallelism for processing. False stands for serial processing of streams.

Stream conversion

Filter method

It can be seen from the name that this is a filter transformation of stream. This method will generate a new stream containing all elements that meet a specific condition.

Operation results:

Map method

The map method refers to some form of transformation of values in a stream. You need to pass it a converted function as an argument.

Flatmap method

When using the map method for stream conversion above, a function is applied to each element and the returned value is collected into a new stream. However, if there is a function, it returns not a value, but a stream containing multiple values. But what you need is a collection of elements from multiple streams.

for example

At this time, you should use flatmap to merge multiple streams, and then collect them into a collection.

Limit method and skip method

The limit (n) method returns a new stream containing n elements (or the original stream if the total length is less than n).

The skip (n) method, on the contrary, discards the previous n elements.

Operation results:

The daily paging function can be realized by using the limit and skip methods:

Distinct method and sorted method

The flow conversion methods described above are stateless. That is, when an element is taken from a converted stream, the result does not depend on the previous element. In addition, there are two methods that need to rely on the elements in the previous flow when transforming the flow. One is the distinct method and the other is the sorted method.

The distinct method will return a stream with the same order and removed duplicate elements according to the elements in the original stream. This operation obviously needs to remember the previously read elements.

Operation results:

The sorted method needs to traverse the entire stream and sort it before generating any elements. Because it is possible that the first element of the sorted set will be in the last bit of the unordered set.

Operation results:

Aggregation operation

The creation and transformation of streams have been described earlier. The following describes the aggregation of streams. Aggregation refers to aggregating streams into a value for use in programs. Aggregation methods are termination operations.

Max method and min method

The count method and sum method used in the previous code example belong to the flow slave aggregation method. There are also two aggregation methods, Max method and min method, which return the maximum and minimum values in the stream respectively.

Operation results:

Findfirst method

The findfirst method returns the first value in a non empty collection, which is usually used in conjunction with the filter method.

Findany method

The findany method can return as long as it finds any matching element in the collection. This method is very effective in parallel execution of streaming (the first matching element found in any fragment will end the calculation, and the serial stream is the same as that returned by findfirst).

Anymatch method

The anymatch method can determine whether there are still matching elements in the collection. The returned result is a Boolean value.

Allmatch method and nonematch method

Allmatch method and nonematch method return true when all elements match and no elements match, respectively.

Although these methods always check the entire flow, they can still improve speed by executing in parallel.

Reduce method

The reduce method is a method to further calculate the elements in the flow.

Operation results

Collect results

After processing the stream, you usually want to see the results rather than aggregate them into a value. The collections class provides us with various factory methods of common collection classes.

Collection collected

For example, the previous example is used to collect a stream into a list. It only needs to be written in this way.

Collected into a set can be used in this way

When a set is collected, you can control the type of set.

Splicing

Concatenate and collect strings from the word stream.

When connecting and collecting strings in the stream, if you want to add a separator in the element mediation, you can pass a joining method.

When the element in the stream is not a string, it needs to be transferred into a string stream before splicing.

Collection aggregation

Collect the sum, average, maximum or minimum of the streams respectively.

Operation results:

The results in the stream are collected at one time and aggregated into a sum, average, maximum or minimum object.

Operation results:

Collect result sets into map

When we want to collect the elements in the collection into the map, we can use collectors Tomap method. This method has two parameters, which are used to generate the key and value of the map.

For example, take the high of a room object as the key and the width as the value

However, there are many cases where specific elements are used as values. You can use function Identity () to get the actual element.

If more than one element has the same key, a Java. Java. XML is thrown when collecting the results Lang.illegalstateexception exception. You can use the third parameter to solve the problem. The third parameter is used to determine how to deal with the result in case of key conflict. If only one and existing values are retained in case of key conflict, it is as follows.

If you want to specify the type of map generated, a third parameter is required.

Note: each toconcurrentmap method will have a corresponding toconcurrentmap method to generate a concurrent map.

Grouping and slicing

In a collection, it is a common function to group values with the same characteristics, and the corresponding methods are also provided in the stream API.

grouping

As in the above example, a room object collection is grouped by height.

Operation results:

Slice

When the classification function is a function that returns a Boolean value, the stream elements are divided into two lists: one is the collection of elements that return true, and the other is the collection of elements that return false. In this case, the partitoningby method is more efficient than groupingby.

For example, we divide the room set into two groups. One group is a room with a height of 22 and the other group is other rooms.

Operation results:

Extended function

The following methods and functions are supported by both the groupingby method and the partitioningby method.

The counting method returns the total number of elements collected.

The summing (int|long|double) method takes a value function as a parameter to calculate the sum.

The maxby and minby methods take a comparator as a parameter to calculate the maximum and minimum values.

Take out the rooms with the largest and smallest width in the group.

Operation results:

The mapping method applies the results to another collector.

Take out the width of the room with the largest width in the group.

Operation results:

No matter groupingby or mapping function, if the return type is int, long or double, you can collect the elements into a summarystatistics object, and then get the sum, average, total, maximum and minimum values of the function values from the summarystatistics object of each group.

Operation results:

Multilevel grouping

In the above examples, we all perform level-1 grouping according to one condition. In fact, groupingby supports multi-level grouping.

For example, at the first level, we group rooms by height and at the second level by width.

Operation results:

Parallel stream

The establishment of stream makes parallel computing easy, but it also needs attention when using parallel stream.

First, it must be a parallel flow. As long as the flow is in parallel mode when terminating the execution of the method, all flow operations will be executed in parallel.

The parallel method can convert any serial stream into a parallel stream.

Second, ensure that the functions passed to parallel stream operations are thread safe.

The code in the above example is wrong, and the operation passed to the parallel stream is not thread safe. You can use the object array of atomicinteger as a counter instead.

We can show the advantage of parallel flow only when we deal with a large amount of set data, and the purpose is to improve efficiency and make use of the resources of multi-core CPU while ensuring thread safety.

Small expansion

When using the stream API, when external variables are referenced during the process of traversing or processing the stream, the variables will be treated as fianl variables by default. So some students will feel that they can't get the index of the collection in the process of traversal. In fact, you can change the idea, you can only traverse the set index, and then take values in the traversal.

The article will be synchronized to my official account.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>