Attention: Java promotion camp, the latest article first time delivery, 10T free learning materials at any time!!

The Stream concept

A Stream is a queue of elements from a data source and supports aggregation operations

The Stream API can greatly improve the productivity of Java programmers, allowing programmers to write efficient, clean, and concise code.

This style treats the collection of elements to be processed as a stream that travels through a pipe and can be processed at the nodes of the pipe, such as filtering, sorting, aggregating, and so on.

Java Stream features

  • A Stream is not a data structure, but a queue of elements from a data source that supports aggregation operations
  • Stream does not change the source data structure
  • Each intermediate operation is delayed and returns a stream, which is processed in the pipe by intermediate operation and finally by terminal operation to get the result of the previous processing

The above process is translated into Java code:

List<Integer> transactionsIds = 
widgets.stream()
             .filter(b -> b.getColor() == RED)
             .sorted((x,y) -> x.getWeight() - y.getWeight())
             .mapToInt(Widget::getWeight)
             .sum();
Copy the code

Generate the Stream

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

  1. Stream () − Creates a serial stream for the collection.
List<String> strings = Arrays.asList("abc".""."bc"."efg"."abcd".""."jkl"); List<String> filtered = strings.stream().filter(string -> ! string.isEmpty()).collect(Collectors.toList());Copy the code
  1. ParallelStream () − Creates parallel streams for collections.
List<String> strings = Arrays.asList("abc".""."bc"."efg"."abcd".""."jkl");
// Get the number of empty strings
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
Copy the code

Operate on Stream

Intermediate Operation

  1. Map: The map method is used to map each element to the corresponding result
List number = Arrays.asList(2.3.4.5);
List square = number.stream().map(x->x*x).collect(Collectors.toList());
Copy the code
  1. Filter: The filter method is used to filter out elements by the set criteria
List names = Arrays.asList("Reflection"."Collection"."Stream");
List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
Copy the code
  1. Sorted: The sorted method is used to sort streams
List names = Arrays.asList("Reflection"."Collection"."Stream");
List result = names.stream().sorted().collect(Collectors.toList());
Copy the code
  1. Limit: The limit method is used to get a specified number of streams
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
Copy the code

Terminal Operation

  1. Collect: The collect method is used to return the result of an intermediate operation
List number = Arrays.asList(2.3.4.5.3);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
Copy the code
  1. ForEach: The forEach method is used to iterate over each piece of data in the stream
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
Copy the code
  1. Reduce: The reduce method is used to calculate the elements of a stream and output a value
// The reduce method uses a BinaryOperator as an argument
// In this case, the ans variable starts with a value of 0
List number = Arrays.asList(2.3.4.5);
int even = number.stream().filter(x->x%2= =0).reduce(0,(ans,i)-> ans+i);
Copy the code

The Stream sample

//a simple program to demonstrate the use of stream in java 
import java.util.*; 
import java.util.stream.*; 
  
class Demo 
{ 
  public static void main(String args[]) { 
  
    // create a list of integers 
    List<Integer> number = Arrays.asList(2.3.4.5); 
  
    // demonstration of map method 
    List<Integer> square = number.stream().map(x -> x*x).collect(Collectors.toList()); 

    System.out.println(square); 
  
    // create a list of String 
    List<String> names = Arrays.asList("Reflection"."Collection"."Stream"); 
  
    // demonstration of filter method 
    List<String> result = names.stream().filter(s->s.startsWith("S")). 
                          collect(Collectors.toList()); 
    System.out.println(result); 
  
    // demonstration of sorted method 
    List<String> show = names.stream().sorted().collect(Collectors.toList()); 

    System.out.println(show); 
  
    // create a list of integers 
    List<Integer> numbers = Arrays.asList(2.3.4.5.2); 
  
    // collect method returns a set 
    Set<Integer> squareSet = numbers.stream().map(x->x*x).collect(Collectors.toSet()); 

    System.out.println(squareSet); 
  
    // demonstration of forEach method 
    number.stream().map(x->x*x).forEach(y->System.out.println(y)); 
  
    // demonstration of reduce method 
    int even = number.stream().filter(x->x%2= =0).reduce(0,(ans,i)-> ans+i); System.out.println(even); }}Copy the code

Output:

[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6
Copy the code