Lebyte-Java 8 Core Feature Stream (Stream)

Time:2019-9-14

Hello, everyone. I’m Lebyte’s Xiaole. Speaking of flow, we will associate with mobile phones, computer assembly lines, logistics warehouse commodity packaging lines and so on. If mobile phones, computers, parcels are regarded as the final result, then all kinds of parts before processing commodities can be regarded as data sources, while a series of processing operations in the middle can be regarded as flow processing.
Lebyte-Java 8 Core Feature Stream (Stream)

I. concept

The operation of stream in Java Se has input-output IO stream, and Stream introduced in Java 8 belongs to a new member of Java API. It allows you to deal with data sets declaratively. Stream provides a high-order extraction of Java set operation and expression by using an intuitive way similar to SQL statement to query data from database. Elephant. Note that the stream operation here can be seen as the processing of aggregated data.

Simply put, a stream is a data channel that operates on the sequence of elements produced by data sources (collections, arrays, files, etc.).

  • Source-stream uses a source that provides data, such as collections, arrays, or input | output resources.

    When generating streams from ordered sets, the original order is preserved. Streams generated by lists in the same order of elements as lists

  • Element Sequences – Like collections, streams also provide an interface to access a set of ordered values of a particular element type.
  • Data Processing Operations – Data processing functions of streams support operations similar to those of databases (data filtering, filtering, sorting, etc.).
  • Pipelining – Multiple streaming operations themselves return to a stream, and multiple operations can be linked together to form a pipeline for data processing.

2. Flow-Set

  • Period of calculation

Lebyte-Java 8 Core Feature Stream (Stream)

The data in the collection are all computed data, such as querying user records from the database in descending order according to user ID query and receiving user records through list. The calculation of data is completed before putting it into the collection.

Data in the stream is computed on demand. Data is computed according to user’s needs, such as searching through search engine. The searched items are not all presented, and the first 10 or 20 items are displayed first. Only when the next page is clicked, the new 10 items will be output. The same is true of stream computing. Stream calculates and processes stream data only when users need corresponding data.

  • External Iteration and Internal Iteration

Lebyte-Java 8 Core Feature Stream (Stream)

If the collection is compared to a warehouse of a factory, at first the hardware of the factory is relatively backward, what modifications should be made to the goods. At this time, the workers go into the warehouse to process the goods themselves, and sometimes transfer the processed goods to another warehouse. At this point, developers need to iterate in person, one by one to find the goods they need, and process them, which is called external iteration.

When the factory develops, it is equipped with pipeline operation. As long as the factory designs the corresponding pipeline according to the demand, then the workers can wait to receive the results as long as they put the goods on the pipeline, and the pipeline can also directly deliver the goods to the corresponding warehouse according to the requirements. This is called internal iteration. Pipelining has helped you complete the iteration. You just need to say what you want to do (that is, to design a reasonable pipeline). Stream, which is equivalent to the introduction of Java 8, implements “automation” of data processing.

3. Flow operation process

Lebyte-Java 8 Core Feature Stream (Stream)

The whole flow operation is a pipeline, where elements are processed one by one. It should be noted that many stream operations themselves return a stream, so multiple operations can be connected directly. As shown in the figure below, operations can be invoked in a chain way, and parallel streams can also implement parallel processing operations of data streams.

Lebyte-Java 8 Core Feature Stream (Stream)

In general, the flow operation process is divided into three stages:

  • Establish

    Creating Stream Objects with Data Sources

  • Intermediate processing

    Intermediate operations such as filtering, slicing, mapping, sorting, etc.

  • Stop flow

    Termination operations such as matching, summarizing, grouping, etc.

IV. Establishment of Flow

Convection operations first create the corresponding flow, which is created in the form of a centralized set as follows:
Lebyte-Java 8 Core Feature Stream (Stream)

4.1 Collection Creation Stream

In Java 8, the collection interface has two ways to generate streams:

  • Stream () Creates a serial stream for a collection.
  • ParallelStream () Creates parallel flows for collections.

The sample code is as follows:

public static void main(String[] args) {
    /**
         * Define set L1 and create a serial stream for the set
         */
    List < String > L1 = Arrays. asList ("Zhou Xingchi", "Zhou Jielun", "Zhou Xingxing", "Zhou Runfa");
    // Return Serial Stream
    l1.stream();
    // Return parallel flow
    l1.parallelStream();
}

In addition to the basic operation of creating the flow, there are several ways to create the flow.

4.2 Value Creation Flow

Stream. of (T...): Stream. of ("aa", "bb") generates streams

// Value creation stream generates a string stream
Stream<String> stream = Stream.of("java8", "Spring", "SpringCloud");
stream.forEach(System.out::println);

4.3 Array Creation Flow

Create the corresponding stream according to the array type of the parameter.

  • Arrays.stream(T[ ])
  • Arrays.stream(int[ ])
  • Arrays.stream(double[ ])
  • Arrays.stream(long[ ])

    /**

    • Let’s take int as an example. Long double is no longer an example.
*/
 Stream stream = Arrays.stream(Arrays.asList(10, 20, 30, 40).toArray());
 // Create a specified Stream based on the array index range
 stream = Arrays.stream(Arrays.asList(10, 20, 30, 40).toArray(), 0, 2);

4.4 File Generation Stream

stream = Files.lines(Paths.get("C:\java\jdbc.properties"));
System.out.println(stream.collect(Collectors.toList()));
// Specifies character set encoding
stream = Files.lines(Paths.get("C:\java\jdbc.properties"), Charset.forName("utf-8"));
System.out.println(stream.collect(Collectors.toList()));

4.5 Function Generated Flow

Two methods:

  • Iterate: Apply functions to each newly generated value in turn
  • Generate: Accepts a function and generates a new value

    // Heavy 100 Begins to Generate Even Flow
    Stream.iterate(100, n -> n + 2);
    // Generate 1-100 random numbers
    Stream.generate(() ->(int) (Math.random() * 100 + 1));

V. Flow Intermediate Operation

Intermediate operations of streams are classified into three categories: filtering slices, mapping and sorting.

Screening slices: Similar to where conditional judgment in sql, elements are screened

Mapping: Conversion of element results, with advantages similar to those of select fields or transformation of element content

Sorting: better understanding, commonly used SQL operation by field ascending and descending order
Lebyte-Java 8 Core Feature Stream (Stream)

Data preparation for midstream operations (take order data processing as an example)

@Data
public class Order {
    // order ID
    private Integer id;
    // order user ID
    private Integer userId;
    // Order Number
    private String orderNo;
    // Order Date
    private Date orderDate;
    // Receiving address
    private String address;
    // Creation time
    private Date createDate;
    // Update time
    private Date updateDate;
    // Order status 0 - unpaid 1 - paid 2 - pending shipment 3 - shipped 4 - received 5 - completed
    private Integer status;
    // Is it valid 1 - valid order 0 - invalid order
    private Integer isValid;
    // Total order amount
    private  Double total;
  }

Order order01 = new Order(1, 10, "20190301",
                New Date (), "Shanghai - Pudong District", new Date (), new Date (), 4, 1, 100.0);
Order order02 = new Order(2, 30, "20190302",
                    New Date (), "Beijing Sihui District", "New Date ()," New Date (), "New Date ()", 1, 1, 2000.0;
Order order03 = new Order(3, 20, "20190303",
                    New Date (), "Beijing - Chaoyang District", new Date (), new Date (), 4, 1, 500.0;
Order order04 = new Order(4, 40, "20190304",
                    New Date (), "Beijing - Daxing District", new Date (), new Date (), 4, 1, 256.0);
Order order05 = new Order(5, 40, "20190304",
                    New Date (), "Shanghai - Songjiang District", new Date (), new Date (), 4, 1, 1000.0;
ordersList = Arrays.asList(order01, order02, order03, order04, order05);

6. Screening & Slicing

  • Screening for valid orders

    // Filter valid orders
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    .forEach(System.out::println);
    
  • Select valid orders for the first page of data (2 records per page)

    // Filter valid orders for the first page of data (2 records per page)
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

     .limit(2)
     .forEach(System.out::println);
    
  • Screen the order set for valid orders and take the last record

    // Filter the order set to take the last record of the valid order
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    Skp (ordersList. size () - 2) // skip the previous ordersList. size () - 2 record
    .forEach(System.out::println);
  • Screen valid orders for page 3 data (2 records per page)

    // Filter valid orders, take page 3 data (2 records per page) and print them to the console
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    .skip((3 - 1) * 2)
    .limit(2)
    .forEach(System.out::println);
    
  • Screening invalid orders to remove duplicate order number records

    // Rewriting Order equals and hashCode methods for filtering invalid orders and eliminating duplicate order number records
    ordersList.stream().filter((order) -> order.getIsValid() == 0)

    .distinct()
    .forEach(System.out::println);
    

Seven, mapping

  • Filter valid orders to get all order numbers

    // Filter valid orders to get all order numbers
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    .map((order) -> order.getOrderNo())
    .forEach(System.out::println);
    
  • Filter valid orders and separate the city information of the receiving address under each order

    ordersList.stream().map(o -> o.getAddress()

    .split("-"))
    .flatMap(Arrays::stream)
    .forEach(System.out::println);
    

Eight, sort

  • Filter valid orders and sort them according to user ID

    // Filter valid orders and sort them according to user ID
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    .sorted((o1, o2) -> o1.getUserId() - o2.getUserId())
    .forEach(System.out::println);    
    

    // Or equivalence
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    .sorted(Comparator.comparingInt(Order::getUserId))
    .forEach(System.out::println);
    
  • Filter valid orders and sort them according to order status. If order status is the same, create time order based on order

    // Filter valid orders if the order status is the same, sort them according to the order creation time, and sort them according to the order status instead
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    .sorted((o1, o2) -> {
        if (o1.getStatus().equals(o2.getStatus())) {
            return o1.getCreateDate().compareTo(o2.getCreateDate());
        } else {
            return o1.getStatus().compareTo(o2.getStatus());
    }})
    .forEach(System.out::println);
    
    

    // Equivalent Form
    ordersList.stream().filter((order) -> order.getIsValid() == 1)

    .sorted(Comparator.comparing(Order::getCreateDate)
    .thenComparing(Comparator.comparing(Order::getStatus)))
    .forEach(System.out::println);
    

9. Flow termination operation

Termination generates results from the pipeline of the stream. The result is any values that are not streams, such as common Lists, Integers, and even voids. There are three types of termination operations for streams:

Lebyte-Java 8 Core Feature Stream (Stream)

10. Finding and Matching

  • Screening whether all valid order matches are paid orders

    // Screening whether all valid order matches are paid orders
    System.out.println (“all Match Match Matching Results:”)+

                     ordersList.stream()
                           .filter((order) -> order.getIsValid() == 1)
                        .allMatch((o) -> o.getStatus() != 0)
                  );
    
  • Screening for valid order matching for unpaid orders

    // Screening for valid order matching for unpaid orders
    System. out. println (“AnyMatch Match Matching Results:”)+

                     ordersList.stream()
                           .filter((order) -> order.getIsValid() == 1)
                           .anyMatch((o) -> o.getStatus() == 0)
                  );
    
  • Screening of all outstanding orders for valid orders

    // Screening of all outstanding orders for valid orders
    System.out.println (“noneMatch matching result:”)+

                    ordersList.stream()
                        .filter((order) -> order.getIsValid() == 1)
                        .noneMatch((o) -> o.getStatus() == 5)
                  );
    
  • Screening valid orders to return the first order

    // Screening valid orders to return the first order

    System.out.println ("FindAny Matching Results:")+
                               ordersList.stream()
                                  .filter((order) -> order.getIsValid() == 1)
                                  .findAny()
                                    .get()
                          );
  • Screen all valid orders to return the total number of orders

    // Screen all valid orders to return the total number of orders

    System.out.println ("count result:")+ 
                            ordersList.stream()
                                .filter((order) -> order.getIsValid() == 1)
                                .count()
                        );
  • Screening the Maximum Order Amount Returned from Valid Order

    // Screening the Maximum Order Amount Returned from Valid Order

    System.out.println ("maximum order amount:")+ 
                               ordersList.stream()
                                .filter((order) -> order.getIsValid() == 1)
                                .map(Order::getTotal)
                                .max(Double::compare)
                                .get()
                          );
  • Screening the Minimum Order Amount of Valid Order Return

    // Screening the Minimum Order Amount of Valid Order Return

    System.out.println ("minimum order amount:")+ 
                                   ordersList.stream()
                                    .filter((order) -> order.getIsValid() == 1)
                                    .map(Order::getTotal)
                                    .min(Double::compare)
                                    .get()
                          );

Reduction-Collection

11.1 reduction

The operation of combining elements in the stream repeatedly to get a value
  • Calculate the total amount of valid orders

    // Calculate the total amount of valid orders

    System.out.println ("Total Valid Order Amount:")+ 
                            ordersList.stream()
                                .filter((order) -> order.getIsValid() == 1)
                                .map(Order::getTotal)
                                .reduce(Double::sum)
                                .get()
                          );

11.2 Collector Data Collection

The stream is converted to other forms, and the coollect method acts as a terminal operation, receiving an implementation of the Collector interface, which is used to aggregate elements in Stream. The most commonly used method is to collect all elements in a stream into a List, Set, or Collection

11.3 Collection

Common collection methods toList, toSet, toCollection, toMap, etc.

  • Screen all valid orders and collect order lists

    // Screen all valid orders and collect order lists
    ordersList.stream()

    .filter((order) -> order.getIsValid() == 1)
    .collect(Collectors.toList())
    .forEach(System.out::println);
    
  • Select all valid orders and collect order number and order amount

    // Select all valid orders and collect order number and order amount
    Map<String,Double> map=ordersList.stream().filter((order) -> order.getIsValid() == 1).

    collect(Collectors.toMap(Order::getOrderNo, Order::getTotal));

    // Traversing the map under Java 8 will cause errors if the Key of the Map is repeated
    map.forEach((k,v)->{

    System.out.println("k:"+k+":v:"+v);

    });

Summary

Summary operations are common in Stream stream operations, such as calculating the total number and average operations. The commonly used methods are as follows:
Lebyte-Java 8 Core Feature Stream (Stream)

The relevant operations are as follows

  • Screen all valid orders to return the total number of orders

    System.out.println (“count result:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .collect(Collectors.counting())
                  );

    System.out.println (“count result:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .count()
                  );
    
  • Return the total order amount

    System.out.println (“Total Order Amount:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .collect(Collectors.summarizingDouble(Order::getTotal))
                  );

    System.out.println (“Total Order Amount:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .mapToDouble(Order::getTotal)
                               .sum()
                  );

    System.out.println (“Total Order Amount:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .map(Order::getTotal)
                               .reduce(Double::sum)
                               .get()
                  );
    
  • Return user id = 20 valid order average amount per purchase

    System.out.println (“User id = 20 valid orders average amount per purchase:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .filter((order -> order.getUserId()==20))
                               .collect(Collectors.averagingDouble(Order::getTotal))
                  );

    System.out.println (“User id = 20 valid orders average amount per purchase:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .filter((order -> order.getUserId()==20))
                               .mapToDouble(Order::getTotal)
                               .average()
                               .getAsDouble()
                  );
    

    System.out.println (“User id = 20 valid orders average amount per purchase:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .filter((order -> order.getUserId()==20))
                               .collect(Collectors.summarizingDouble(Order::getTotal))
                               .getAverage()
                  );
    
  • Screening all valid orders and calculating the total order amount

    System.out.println (“Total Order Amount:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .collect(Collectors.summingDouble(Order::getTotal))
                  );
    

XIII. Maximum

  • Screening all valid orders and calculating the minimum order amount

    System.out.println (“Minimum order amount:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .map(Order::getTotal)
                               .collect(Collectors.minBy(Double::compare))
                  );
    
  • Screening all valid orders and calculating the maximum order amount

    // Screening all valid orders and calculating the maximum order amount
    System.out.println (“Maximum Order Amount:”)+

                           ordersList.stream()
                               .filter((order) -> order.getIsValid() == 1)
                               .map(Order::getTotal)
                               .collect(Collectors.maxBy(Double::compare))
                  );
    

14. Grouping-Zoning

14.1 grouping

GroupingBy is used to group data and eventually return a Map type. The second parameter of groupingBy is used to implement multilevel grouping.

  • Grouping operations based on payment status of valid orders

    Map<Integer,List<Order>> g01=ordersList.stream()

                                .filter((order) -> order.getIsValid() == 1)
                                .collect(Collectors.groupingBy(Order::getStatus));

    g01.forEach((status,order)->{

    System.out.println("----------------");
    System.out.println ("order status:"+status);
    order.forEach(System.out::println);

    });

  • Screening valid orders and grouping them according to user ID and payment status

    Map<Integer,Map<String,List<Order>>> g02= ordersList.stream()

    .filter((order) -> order.getIsValid() == 1)
                    .collect(Collectors.groupingBy(Order::getUserId,
                              Collectors.groupingBy((o)->{
                                    if(o.getStatus()==0){
                                        Return "unpaid";
                                    }else if (o.getStatus()==1){
                                        Return "paid";
                                    }else if (o.getStatus()==2){
                                        Return "to be shipped";
                                    }else if (o.getStatus()==3){
                                        Return "shipped";
                                    }else if (o.getStatus()==4){
                                        Return "received";
                                    } else{
                                        Return "completed";
                                    }
                                }
                                ))
                            );

    g02.forEach((userId,m)->{

    System.out.println ("User id:"+userId+"--> The valid order is as follows:");
    m.forEach((status,os)->{
        System.out.println ("status:"+status+"- - order list is as follows:");
        os.forEach(System.out::println);
    });
    System.out.println("-----------------------");

    });

14.2 partition

The difference between partitioning and grouping is that partitioning is divided by true and false, so the lambda of partitioning By’s parameter is also T – > Boolean

  • Zoning Operation – Screening Valid Orders with Order Amount > 1000

    Map<Boolean,List<Order>> g03= ordersList.stream()

            .filter((order) -> order.getIsValid() == 1)
            .collect(Collectors.partitioningBy((o)->o.getTotal()>1000));

    g03.forEach((b,os)->{

    System.out.println ("partition result:"+b+"- list result:");
    os.forEach(System.out::println);

    });

  • Stitching Operation – Screening Effective Orders and Stitching

    String orderStr=ordersList.stream()

            .filter((order) -> order.getIsValid() == 1)
            .map(Order::getOrderNo)
            .collect(Collectors.joining(","));

    System.out.println(orderStr);

Application of Flow

Java 8 introduces Stream stream operation, which makes the processing of elements more convenient and fast. It combines Lambda, functional interface, method reference and other related contents well through Stream related methods, which makes the processing of streams much simpler than the original set processing code. Stream supports chain call of functions, which makes the code more convenient. Compact parallel processing of elements supported by Stream at the same time improves the performance of program execution. The application of Stream stream is usually used in the data processing of set elements, especially when elements need to be processed many times. At the same time, it has a stronger flavor of functional programming, which is also a trend of future development.

Well, the Stream stream of Java 8 core features is introduced here. It should be very detailed. I hope you like it and pay more attention to Xiaole. Xiaole will bring you more skilled goods. Happy Dragon Boat Festival and Happy Learning!

Recommended Today

Analysis of new data type instances of ES6 learning notes

An example of this paper describes the new data types of ES6 learning notes. To share with you for your reference, as follows: 1. Data deconstruction assignment 1. Deconstruction and assignment of arrays Basic usage: let [key1, key2…] = [value1, Value2…] Let [name, age, sex] = [‘xiaoming ‘, 24,’ male ‘]; console.log(name); console.log(age); console.log(sex); Note […]