This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

Java 8 Stream allows us to process data in steps and nodes like a pipeline. Java 8 Stream programming, also known as streaming programming, converts a collection of data into a single data Stream that is collected in a new container (usually a collection) after a series of processes as the data flows from the source to the destination. It’s kind of like a factory assembly line.

Section Stream data source (1, 2, 3, 10): 7 Section plus one (2, 3, 4, 11): 6 Section filters data greater than 10 (2, 3, 4): 5 Section collect package data [2, 3, 4]: 4

The data in the flow flows one by one to the next processing node and is finally aggregated by the collector

Streams can be divided into three categories, based on how data is processed in the stream: creation, processing, and termination

create

There are two ways to create a Stream: directly or based on a collection instance

Directly to create

Use Stream of, generate, empty, concat, iterate, and create streams directly

  • of: is created directly using the element
  • generateUse:SupplierThe provided element is created
  • empty: Creates an empty oneStream
  • concat: Connect twoStreamReturn a newStream
  • iterate: Applies the function f iteration to the infinite order generated by the initial element SEEDStream

Create based on the collection instance

Java 8CollectionAdded default methods to the interfacestreamandparallelStreamThese two methods are created from collection elementsStream In additionjava.util.ArraysClass is also addedstreamMethod to create from an arrayStream Example:

ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
Stream<Integer> stream = arrayList.stream();

Set<String> hashSet = new HashSet<>();
hashSet.add("A");
hashSet.add("B");
Stream<String> stream1 = hashSet.stream();

Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("A".1);
hashMap.put("B".2);
// Map does not inherit the Collection interface, so it needs to be converted to Set first
Stream<Map.Entry<String, Integer>> stream2 = hashMap.entrySet().stream();

String[] strings = {"a"."b"};
Stream<String> stream3 = Arrays.stream(strings);
Copy the code

To deal with

Processing is like adding dry steps one by one on the pipeline, mainly including conversion, filtering, sorting and other operations

The debug view

  • peek: Accept oneConsumerParameter, does not change the original data

conversion

  • map: Accept oneFunctionParameter, the data in the stream will be replaced byFunctionThe return value of the
  • flatMap: Accept oneFunctionParameters,FunctionThe return value of isStreamType,flatMaptheFunctionThe return value of isStreamJoin together

Example:

To heavy filtering

  • filter: Accept onePredicateParameters, elements asserted as true flow to the next operation, and elements asserted as false are filtered
  • distinct: Eliminates duplicate elements in the flow

Example:

The sorting

  • sorted(): sorting
  • sorted(Comparator): sort according toComparatorThe sorting

Example:

Limit and Skip

  • limit: takes an int argument and retains the number of elements
  • skip: takes an int and skips the first n elements

Example:

Termination of

Terminating an operation is the last step in data processing in the flow. After the termination operation is completed, the stream no longer exists and cannot be consumed again. Termination can be divided into: collection, combination, array, match, find, statistics

collect

  • collect(Collector): Accept oneCollectorParameter, using the collector to collect stream elements into the collection
  • collect(Supplier, BiConsumer, BiConsumer): Accepts three parametersSupplier,BiConsumer,BiConsumerTo collect the flow elements into the collection. The first parameterSupplierCreate a new collection, second parameterBiConsumerGathers the next element into the result set, the third parameterBiConsumerUsed to combine two result sets

Example:

combination

  • reduce: Accept oneBinaryOperatorParameter, useBinaryOperatorTo combine all the elements in the flow. The return value isOptionaltype
  • reduce: Accept parameteridentity,BinaryOperator, function is the same as above.identityAs an initial value for its combination. So if the stream is emptyidentityIs the result

Example:

Turn an array

  • toArray(): Converts the stream into an array of the appropriate type
  • toArray(generator): Generates an array of custom types

Example:

matching

  • allMatch: Accept onePredicateParameter, the result returns true if every element of the stream is asserted to true. Return false when the first assertion is false
  • anyMatch: Accept onePredicateParameter, returns true if any element of the stream is asserted to true. Returns true if the first assertion is true
  • noneMatch: Accept onePredicateParameter, which returns true if every element of the stream is asserted as false. Return false when the first assertion is true

Example:

To find the

  • findFirst: returns the first element in the streamOptionalReturns if the stream is emptyOptional.empty
  • findAny: returns any element in the streamOptionalReturns if the stream is emptyOptional.empty

Example:

statistical

  • count: returns the number of elements in the stream.
  • max: Accept oneComparatorParameter, returnComparatorThe largest element to be compared
  • min: Accept oneComparatorParameter, returnComparatorThe smallest element to compare

The following operation can only be used for IntStream, LongStream, DoubleStream

  • average: Takes the average value of stream elements
  • sum: Sums all stream elements
  • summaryStatistics: Generates potentially useful data, including maximum, minimum, average, and so on

Example: