In this chapter we will learn about the stream API, a new feature in JDK 8. To understand the topic of this chapter, you need to know how to use lambda expressions and predefined functional interfaces in Java.util.function.
A stream is similar to a pipe, but it transports not water and oil, but transports the data from the source to the destination. A stream can be parallel and concurrent, depending on how it is passed. A parallel stream can be useful for running on a multi-core CPU machine.
At first glance, a stream is like a collection container, but it is not a data structure used to store objects, it is only responsible for moving objects, so you can't think of it as a collection object to add data to it.
The main reason for using stream is that it supports parallel and concurrent aggregation operations. For example, you can easily filter, sort, or map elements from within a stream.
The different types of Stream APIs are in the Java.util.stream package. Where the stream interface is the most commonly used stream type in this area. A stream can pass any type of object, and there are several specialized streams:Intstream, longstream, and Doublestream. They are all from BaseStream.
The following table shows some of the methods that are common in the stream interface:
Method |
Describe |
Concat |
Lazy loading the way to connect two stream. Returns a new stream whose elements include all elements of the two stream. The element of the first stream is followed by the second stram element. |
Count |
Returns the number of elements within the stream. |
Empty |
Creates and returns an empty stream. |
Filter |
Returns a new stream in all elements of the stream, based on the given assertion interface. |
Foreach |
Performs an action on each element of the stream. |
Limit |
Returns a new stream from the current stream, based on the number of specified maximum elements. |
Map |
Returns the stream that contains the result of the given method that is applied to the element of stream. |
Max |
Returns the largest element in the stream according to the comparer. |
Min |
Returns the smallest element in the stream according to the comparer. |
Of |
Returns a stream that has a value given. |
Reduce |
Use a unique ID and accumulator on the stream to perform the decrement operation. |
Sorted |
Returns a new stream that uses a natural sort. |
ToArray |
Returns an array containing all the elements of the stream. |
Some stream methods perform an intermediate procedure, and some perform the final operation. The intermediate procedure transfers a stream to another stream. Such methods as filter,map,sorted.
The method that performs the final operation produces results or other effects. For example, Count,foreach is the operation that performs the final result.
The operation of the intermediate process is lazy loading, he will not really execute, only the final result will be the actual start of the calculation on the source.
Upgrading to Java 8--Chapter fourth the Stream API