Java Stream Stream thought

 

Speaking Stream it is easy to think of I / O Stream, in fact, who prescribed "flow" it must be "IO stream" mean? In Java 8 in, thanks to functional programming Lambda brought about by the introduction of a new the Stream concept, has been used to solve the drawbacks of the existing library collections.

introduction

Conventional multi-step through code set

Almost all of the set (e.g., Collection interface or Map interface, etc.) are directly or indirectly support the traversal operations. And when we need to operate elements of the collection, in addition to adding necessary, Delete, Get, the most typical is a collection of traversal. E.g:

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class DemoForEach {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        Collections.addAll(list, "Java", "C", "Python", "Hadoop", "Spark");

        for (String s : list) {
            System.out.println(s);
        }
    }
}

Run the program, the console output:

Java
C
Python
Hadoop
Spark

This is a very simple set of traversal operations: each of the set of strings are a print output operation.

 

Loop through drawbacks

Java Lambda 8 so that we can focus more on what to do (What), rather than how to do (How).

Now, we carefully understand what the example code, you can find:

  • for loop syntax is "how to do"

  • Loop for loop is the "what"

Why cycling? Because you want to be traversed. But cycling is the only way to traverse it? Traversal means for processing each element individually, and not cycle from first to last a sequential process. The former is the goal, which is the way.

 

Imagine, if you want to set filter element filter:

  1.  A set according to conditions of the filter as a subset of B;

  2. The second condition and then filtered subset C.

How to do that in practice before 8 Java might be?:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DemoNormalFilter {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "Java", "C", "Python", "Hadoop", "Spark");

        Of System.out.print ( "set before screening:" );
         for (S String: List) {
            System.out.print(s + ",");
        }
        System.out.println();

        Of System.out.print ( "after the screening conditions set 1:" );
         for (S String: List) {
             IF (s.length ()> =. 4 ) {
                System.out.print(s + ",");
            }
        }
        System.out.println();

        Of System.out.print ( "Condition 2 after screening set:" );
         for (S String: List) {
             IF (s.length ()> =. 5 ) {
                System.out.print(s + ",");
            }
        }
        System.out.println();
    }
}

Run the program, the console output:

A collection of pre-screening: Java, C, Python, Hadoop, Spark,
After a set of conditions after screening 1: Java, Python, Hadoop, Spark,
After a set of conditions after screening 2: Python, Hadoop, Spark,

This code contains three cycles, each of a different function:

1, from beginning to end first traverse output set.

2, then filter element string length greater than or equal to 4, and outputs.

3, the last filter element string length greater than or equal to 5, and outputs.

 

Whenever we need to set the elements to operate, always need to cycle, cycle, recycle. This is of course what? Not. Cycling is a way of doing things, not an end. On the other hand, using a linear traversal cycle means that only once. If you want to traverse again, and then use another cycle can only start from scratch.

So, Lambda derivatives Stream can bring us what more elegant wording it? Here we look at the wording of Stream's better.

 

Stream more preferably wording

The following look at Java Stream API 8 of aid, what is meant by elegant:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Demo01Stream {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "Java", "C", "Python", "Hadoop", "Spark");

        list.stream()
                .filter((s) -> s.length() >= 4)
                .filter((s) -> s.length() >= 5)
                .forEach((s) -> System.out.println(s));
    }
}

Run the program, the console output:

Python
Hadoop
Spark

Consistent with the above example of the results of screening.

Reading the code directly to the literal meaning of the semantic perfect display of logically independent: an acquisition stream, the filter length is less than 4, the filter length is less than 5, the printing one by one. The code does not reflect the use of linear cyclic or any other algorithm to traverse, we really need to do is to better reflect the contents of the code.

 

The above method used by the program:

stream () method

Using stream () method to obtain the stream. This method is a method java.util.Collection default interface, the method follows the source:

// returns the collection of the source sequence flow. 
default Stream <E> Stream () {
     return StreamSupport.stream (spliterator (), to false );
}

 

filter () method

This method is java.util.stream Stream Interface package in an abstract method, the following method Source:

// return flow by a given stream {predicate} This matching element thereof. 
Stream <T> filter (Predicate <? Super predicate T>);

The return value is a process flow parameter is a function of the incoming interface:. Java.util.function the Predicate , the interface may be determined for certain types of data, and return a Boolean value.

 

forEach () method

This method is java.util.stream Stream Interface package in an abstract method, the following method Source:

// the operation to each elementary stream. 
void forEach (Consumer <? Super T> Action);

This method does not return a value, a function is passed the parameter interface:. Java.util.function Consumer . Its role is: a consumer data, its data type is determined by generics.

 

Examples of the above code can be improved:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Demo02Stream {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "Java", "C", "Python", "Hadoop", "Spark");

        list.stream()
                .filter((s) -> s.length() >= 4)
                .filter((s) -> s.length() >= 5)
                .forEach(System.out::println);
    }
}

In fact, we modified the forEach () method in the incoming parameters,

System.out::println
(s) -> System.out.println(s)

The two are equivalent.

 

Streaming Overview ideas

Note: Please Forget the stereotype of the traditional IO streams!

Overall, the idea is similar to the factory floor flow "production line."

 

When the need for multiple elements to operate (especially multi-step operation), taking into account performance and convenience, we should first of all a good fight a "model" step program, and then follow the program to execute it.

This is shown in FIG filtering, mapping, skip, counting multiple operations, it is a process scheme of a collection of elements, while the program is a "function model." FIG Each block is a "flow", the method invokes the specified, another flow may be a flow model from the model conversion. The rightmost digit 3 is the final result.

 

Here the filter, Map, Skip is operating in a function model, a collection of elements and not actually processed. Only when the end of the method when the count carried out, the entire operation will be performed in accordance with the model specified policy. And thanks to the delay in the implementation of the Lambda characteristic .

Note: "Stream Flow" is actually a collection of elements of the model function, it is not set, the data structure is not, in itself does not store any element (or address value).

 

Stream (flow) is an element from the data source queue

  • Element is a particular type of object, a queue is formed. In Java Stream and does not store elements, but on-demand computing.

  • Source: source stream. It may be a collection, such as an array.

 

Previous Collection operate different, Stream operation there are two basic characteristics:

  • Pipelining: intermediate operations return stream object itself. Such operations may be connected in series to a plurality of pipes, as flow style (fluent style). This will optimize the operation, such as delayed execution (laziness) and short circuit (short-circuiting).

  • Internal iterations: In the past the collection is traversed by Iterator or enhanced for the way, in an explicit set of external iterate, this is called an external iteration. Stream provides a way inside iterative flow traversal method can be called directly.

 

When a stream of time, typically includes three basic steps of: obtaining a data source (Source) → data conversion → performs operation of obtaining the desired result, converting each Stream object does not change the original, a new Stream object returns ( there may be multiple conversions), which may be arranged to allow the operation same as the chain thereof, into a conduit.

 

Guess you like

Origin www.cnblogs.com/liyihua/p/12288600.html
Recommended