Son odd take you into the world Java8 flow (a)

    Prior to said stream, we take a look at the collection, and why? As Java8 a new member, and it has a collection of many similarities, but they also can be transformed into each other. Not just a collection of Java language, any notion of a language has a set of advanced development, the collection name suggests, is a lot of data sets together, it can be considered a container, we can also use generics to limit the type of data collection.

First, what is the flow

    As a new member of Java8 flow, which allows us to declarative way to deal with data collection. We can see it as through the data set high-level iterators. In addition, the flow can also be transparently processed in parallel, which makes us without writing multithreaded code. In the subsequent let us talk of parallel flow streams and detail.

    Did not talk much, we use a piece of code to visually compare the difference between before and after Java8:

. 1  Package com.hz;
 2  
. 3  Import Classes in java.util *. ;
 . 4  
. 5  Import  static java.util.stream.Collectors.toList;
 . 6  
. 7  public  class StreamDemo {
 . 8      public  static  void main (String [] args) {
 . 9          List < police> Polices = Arrays.asList (
 10                  new new police ( "P001", "more than police officers," 27, "Zhejiang" ),
 11                  new new police ( "P002", "Lee police officer," 32, "Anhui" ),
 12                  new new police ( "P003", "Cheng police officers," 25, "Anhui"),
13                 newPolice ( "P004", "Young police officer," 35, "Zhejiang" ),
 14                  new new Police ( "P005", "Zhang police officers," 31, "Shanghai" ),
 15                  new new Police ( "P006", "King of police officers" , 42, "Zhejiang" ),
 16                  new new Police ( "P007", "Zhao officer", 31, "Zhejiang" ),
 . 17                  new new Police ( "P008", "Liu police officer", 49, "Zhejiang" ),
 18 is                  new new Police ( "P009", "Week officer", 32, "Zhejiang" )
 19          );
20  
21          // problem: the above collection of police, more than 30-year-old police screened and sorted according to age, the screening results are stored in the police the name of another set of 
22  
23          / ** ******* ************************** Java7 achieve the above problem ******************** *************************** * / 
24         List<Police> tempList = new ArrayList<>();
25         for (Police police : polices) {
26             if (police.getPoliceAge() > 30) {
27                 tempList.add(police);
28             }
29         }
30         Collections.sort(tempList, new Comparator<Police>() {
31             @Override
32             public int compare(Police o1, Police o2) {
33                 return Integer.compare(o1.getPoliceAge(), o2.getPoliceAge());
34             }
35         });
 36          List <String> = tempPoliceNameList new new the ArrayList <> ();
 37 [          for (Police Police: tempList) {
 38 is              tempPoliceNameList.add (police.getPoliceName ());
 39          }
 40          System.out.println (tempPoliceNameList);
 41 is  
42 is          System.out.println ( "parting line ------- -------------------------------- -------------------------------- " );
 43 is  
44 is          / ** ********** *********************** Java8 achieve the above problem *********************** ************************ * / 
45         List <String> tempPoliceNameStream = polices.stream () filter. (P -> p.getPoliceAge ()> 30 )
 46 is                  .sorted (Comparator.comparing (Police :: getPoliceAge))
 47                  .map (Police :: getPoliceName)
 48                  . the collect (toList ());
 49          System.out.println (tempPoliceNameStream);
 50          
51 is          // Note: If you want to execute in parallel, in Java8, just to polices.stream () to polices.parallelStreamm () 
52 is      }
 53 is  }
 54 is  
55  results:
 56  [Zhang police, officer Zhao Li officer, circumferential officer, Yang officer, police officer Wang, Liu police officer]
 57 --------------------- ----------- Dividing line------------------------------------- -
 58 [Zhang police officer, police officer Zhao, Li police officer, police officer Zhou Yang police officers, police officer Wang, Liu police officer]

    From the above piece of code, we can see that:

  1, the code is written in a declarative manner. That is you want to accomplish the work, rather than how to do.

  2, operation of the chain can be used. Filter may be directly method after point until completion.

    From the above, we can briefly summarize the benefits of using streams:

  1, declarative: more concise and readable.

  2, reusable: more flexible.

  3, parallel: better performance.

Second, the introduction flow

    I read the above flow and relatively simple collection, then in the end what is it flow? We can simply described as "generated from the source data processing operations support element sequence." We distinguish resolve this sentence:

  ①, the sequence of elements: the collection, like how it is, you can access an ordered set of values ​​for a particular element type. But it is different from the set, is a set of data structure, its main purpose is to store data in a time and space. Primarily used to calculate the flows. They are essentially different.

  ②, Source: source i.e., when processing the data stream, the data source, for example: set may be a source, a source file may be.

  ③, data processing operations: the operation flow is similar to our database, the processing of data such as: filter / map / sort the like. When processing stream data, it can also be sequentially performed in parallel.

    Stream has two obvious features in operation:

  1, lines. I.e., the flow operation returns a stream or, such operation can have a plurality of back links, thereby forming a pipeline.

  2, the internal iteration. In dealing with the flow, we can not see the process, which is performed in the background. We can fancy a return, the police in the screening / sorting / mapped to the back of the interception / how to complete the conversion, we can not see the implementation process.

Three, to set the flow ratio

    In Java8 collection and flow can be transformed each other, but from the point of view of data collection can continue traversal, flows can traverse only once, after the end of a traverse, which represents the completion of the article stream, if you want to process again, We need to re-establish a stream object. If we deal with again a stream has been completed, an exception is thrown.

package com.hz;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamDemo2 {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Java", "JavaScript", "Python");
        Stream<String> stream = list.stream();
        stream.forEach(System.out :: println);

        System.out.println ( "-------- ------ parting line" );

        stream.forEach(System.out :: println);
    }
}

result:
    Java
    JavaScript
    Python
    ------ 分割线 --------
    Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
        at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
        at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
        at com.hz.StreamDemo2.main(StreamDemo2.java:18)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

    Based on the results we know, the operation is complete or stream has been closed. When we want to operate the flow is abnormal.

    We are on an internal flow comes iteration, there is also a collection of iterations, but in general we are a collection of external iteration, this two iterative methods are different?

package com.hz;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class StreamDemo3 {
    public static void main(String[] args) {
        List<Book> books = Arrays.asList(
                new Book("Java入门", "张**"),
                new Book("JavaScript入门", "李**"),
                new Book("Python入门", "王**")
        );

        List <String> = booksName new new the ArrayList <> ();
         // ************ l- done using for-each external iteration 
        for (Book Book: Books) {
            booksName.add(book.getBookName());
        }
        System.out.println(booksName);

        System.out.println ( "--------- --------- parting line" );
        booksName.clear();
        // ************ 2- iterators (iterator back) do external iteration 
        the Iterator <Book> bookIterator = books.iterator ();
         the while (bookIterator.hasNext ()) {
            Book book = bookIterator.next();
            booksName.add(book.getBookName());
        }
        System.out.println(booksName);

        System.out.println ( "--------- --------- parting line" );
        booksName.clear();
        // ************ 1- iteration using the internal flow 
        booksName = books.stream () Map (Book :: getBookName) .collect (toList ()).;
        System.out.println(booksName);
    }

    static class Book {
        private String bookName;
        private String bookAuth;

        public String getBookName() {
            return bookName;
        }

        public void setBookName(String bookName) {
            this.bookName = bookName;
        }

        public String getBookAuth() {
            return bookAuth;
        }

        public void setBookAuth(String bookAuth) {
            this.bookAuth = bookAuth;
        }

        public Book(String bookName, String bookAuth) {
            this.bookName = bookName;
            this.bookAuth = bookAuth;
        }
    }
}

Description: We can see from the above code is 1 process / 2 two iterative we know, but we can not see 3 iterations details.

Fourth, the flow of basic operation

    From one, we can see a piece of code

polices.stream().filter(p -> p.getPoliceAge() > 30) .sorted(Comparator.comparing(Police :: getPoliceAge)) .map(Police :: getPoliceName) .collect(toList());

    For this code we can be divided into two parts or two operations:

  1, from the stream after the method, filter / sorted / map are returned as a stream to form a pipeline.

  2, i.e. close collect method execution flow, and a non-return stream object.

    For these two portions, the first operation will be referred to as an intermediate operation, the second operation called terminal operation.

    In the middle of the operation, the real logic of the code did not execute, only when faced with a terminal operation, before the middle of the operation was started, and know the end of the stream is closed.

    From these, we can summarize downstream mainly contains three things that first source data needed to perform a query, an intermediate chain of operations requires a pipeline stream is formed again, and finally a terminal needs to perform a pipeline operation and return result.

Guess you like

Origin www.cnblogs.com/chuanqi1415583094/p/12157579.html