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 elementgenerate
Use:Supplier
The provided element is createdempty
: Creates an empty oneStream
concat
: Connect twoStream
Return 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 8Collection
Added default methods to the interfacestream
andparallelStream
These two methods are created from collection elementsStream
In additionjava.util.Arrays
Class is also addedstream
Method 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 oneConsumer
Parameter, does not change the original data
conversion
map
: Accept oneFunction
Parameter, the data in the stream will be replaced byFunction
The return value of theflatMap
: Accept oneFunction
Parameters,Function
The return value of isStream
Type,flatMap
theFunction
The return value of isStream
Join together
Example:
To heavy filtering
filter
: Accept onePredicate
Parameters, elements asserted as true flow to the next operation, and elements asserted as false are filtereddistinct
: Eliminates duplicate elements in the flow
Example:
The sorting
sorted()
: sortingsorted(Comparator)
: sort according toComparator
The sorting
Example:
Limit and Skip
limit
: takes an int argument and retains the number of elementsskip
: 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 oneCollector
Parameter, using the collector to collect stream elements into the collectioncollect(Supplier, BiConsumer, BiConsumer)
: Accepts three parametersSupplier
,BiConsumer
,BiConsumer
To collect the flow elements into the collection. The first parameterSupplier
Create a new collection, second parameterBiConsumer
Gathers the next element into the result set, the third parameterBiConsumer
Used to combine two result sets
Example:
combination
reduce
: Accept oneBinaryOperator
Parameter, useBinaryOperator
To combine all the elements in the flow. The return value isOptional
typereduce
: Accept parameteridentity
,BinaryOperator
, function is the same as above.identity
As an initial value for its combination. So if the stream is emptyidentity
Is the result
Example:
Turn an array
toArray()
: Converts the stream into an array of the appropriate typetoArray(generator)
: Generates an array of custom types
Example:
matching
allMatch
: Accept onePredicate
Parameter, the result returns true if every element of the stream is asserted to true. Return false when the first assertion is falseanyMatch
: Accept onePredicate
Parameter, returns true if any element of the stream is asserted to true. Returns true if the first assertion is truenoneMatch
: Accept onePredicate
Parameter, 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 streamOptional
Returns if the stream is emptyOptional.empty
findAny
: returns any element in the streamOptional
Returns if the stream is emptyOptional.empty
Example:
statistical
count
: returns the number of elements in the stream.max
: Accept oneComparator
Parameter, returnComparator
The largest element to be comparedmin
: Accept oneComparator
Parameter, returnComparator
The smallest element to compare
The following operation can only be used for IntStream, LongStream, DoubleStream
average
: Takes the average value of stream elementssum
: Sums all stream elementssummaryStatistics
: Generates potentially useful data, including maximum, minimum, average, and so on
Example: