Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Stream feature of java8

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "what are the Stream features of java8". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Java.util.Stream represents the last sequence of operations that can be applied to a set of elements. Stream operations are divided into intermediate operations or final operations. The final operation returns a specific type of calculation result, while the intermediate operation returns Stream itself, so that multiple operations can be strung together in turn. To create Stream, you need to specify a data source, such as a subclass of java.util.Collection, List or Set, which is not supported by Map. The operation of Stream can be performed by serial stream () or parallel parallelStream ().

I. brief introduction

Java8 has added a new feature: streaming Stream. Stream enables developers to deal with data sources (collections, arrays, etc.) in a declarative manner, focusing on a variety of efficient aggregation operations (aggregate operation) and mass data operations (bulk data operation) on data sources.

Stream API regards the processed data source as a kind of Stream (stream). Stream (stream) transmits and operates in the Pipeline (pipeline). The supported operations include filtering, sorting, aggregation, etc., and get the final processing result when it reaches the end point.

Several key concepts:

The element Stream is a queue of elements from the data source, and Stream itself does not store elements.

The data source (that is, the source of Stream) includes collection, array, I _ channel, generator (generator) and so on.

Aggregation operations are similar to filter, map, find, match, sorted and other operations in SQL

The pipeline operation Stream returns the Stream object itself after the operation in Pipeline, so that multiple operations are concatenated into a Pipeline and form fluent-style code. This approach optimizes operations such as delayed execution (laziness) and short circuit (short-circuiting).

Internal iterations are different from the way java8 used to traverse collections (external iterations). Stream API implements internal iterations using the Visitor pattern (Visitor).

Parallel operation Stream API supports both serial (stream ()) and parallel (parallelStream ()) operations.

Characteristics of Stream API:

The use of Stream API is closely related to the lambda expression, which is also a new feature of java8, which can greatly improve coding efficiency and code readability.

Stream API provides both serial and parallel operations, in which parallel operations can give full play to the advantages of multi-core processors and use fork/join to improve the running speed.

Stream API can write efficient concurrent programs without writing multithreaded code for parallel operations, and it can usually avoid the problem of multithreaded code errors.

Second, simple examples

Let's look at a simple example of counting the number of positive numbers in an array of integers:

Before java8:

Public static void main (String [] args) {List numbers = Arrays.asList (- 1,-2,0,4,5); long count = 0; for (Integer number: numbers) {if (number > 0) {count++ }} System.out.println ("Positive count:" + count);}

After java8:

Public static void main (String [] args) {List numbers = Arrays.asList (- 1,-2,0,4,5); long count = numbers.parallelStream (). Filter (I-> I > 0). Count (); System.out.println ("Positive count:" + count);}

As you can see, in the above example, the filter () method is used to filter the array, the count () method is used to count the size of the filtered array, and the parallelStream () method creates a parallel flow for the collection, automatically using parallel operations to improve speed. In more complex scenarios, forEach (), map (), limit (), sorted (), collect (), and other methods can be used for further flow operations.

III. Detailed explanation of typical interfaces

This section takes a typical scenario as an example, lists the usage of common Stream API interfaces, and appends the corresponding code.

It should be noted that there are many method overloads in Stream API. Only one method with the same name may be listed in this article. Please pay attention to ~

3.1Generation of Stream

Java8 Stream API supports serial or parallel methods. You can simply take a look at the source code of the jdk1.8 Collection interface (comments are only intercepted):

/ * @ return a sequential {@ code Stream} over the elements in this collection * @ since 1.8 * / default Stream stream () {return StreamSupport.stream (spliterator (), false);} / * * @ return a possibly parallel {@ code Stream} over the elements in this collection * @ since 1.8 * / default Stream parallelStream () {return StreamSupport.stream (spliterator (), true);}

As you can see, in the Collection of the collection class, it is generated in two ways:

1. Serial flow: stream ()

two。 Parallel flow: parallelStream ()

It should be noted that after the parallel flow is generated using parallelStream (), the traversal of the collection elements is unordered.

3.2 forEach () method

Take a brief look at the source code of the forEach () method (comments are only partially intercepted):

/ * Performs an action for each element of this stream. * / void forEach (Consumer

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 210

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report