- Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Requirements in the project
[Requirement] : Existing student score table (student NUMBER, course name, and grade) 1. Data with scores higher than 85 need to be deleted and sorted according to their scores from high to low. 2. List
scoreList = new ArrayList<>();
This was done before Java7
The above requirements are quite simple. Anyone who knows a little bit of code should be able to do this. What we emphasize today is not the realization, but the way of the realization. All roads lead to Rome. We’ll do it today with a new Java8 feature called Stream. First let’s take a look at Java7 and even previous implementations.
- Problem 1 code & effect
- Problem two code & effect
- Problem 3 code & effect
Java7 even before we really want to vomit about this kind of requirements, this kind of requirements are database type requirements, why say so because these requirements we can do in SQL would be very convenient. But manipulating data in Java can be tricky. So let’s look at how Java8 is optimized.
The practice of Java8
No comparison, no harm, no stream era we are how sad, with stream we are in the face of database demand we will be easily solved. ,
The Stream definition
Flow operations are divided into intermediate and terminal operations and combined into flow pipes. A Stream pipeline consists of a source (such as a collection, an array, a generator function, or an I/O channel);
Our development prior to Java8 was called imperative programming. Development through stream after Java8 is called declarative development.
A flow processing can be divided into three parts: flow (Head), 】 【 middle operation (StatefulOp (stateful) | StatelessOp (stateless)], [terminal operation]. The intermediate operation of a stream is
- It is inert and does not work until terminal operation.
- Performing an intermediate operation simply generates a new stream
- The stream is destroyed after the terminal operation. Can’t be used again
- Iterator and spliterator are equivalent to extension interfaces. They are used for imperative development in cases where the stream does not provide sufficient functionality.
- In the case of infinite flow as the source, a finite flow is generated by some intermediate filter, which is called short circuit
The table below details which apis are intermediate operations and which are end operations
Stream operation classification | ||
---|---|---|
In the middle of operation | stateless | unordered() filter() map() mapToInt() mapToLong() mapToDouble() flatMap() flatMapToInt() flatMapToLong() flatMapToDouble() peek() |
A stateful | distinct() sorted() sorted() limit() skip() | |
End of operation | Non-short-circuit operation | forEach() forEachOrdered() toArray() reduce() collect() max() min() count() |
Short circuit operation | anyMatch() allMatch() noneMatch() findFirst() findAny() |