Article Directory
- 1. What is stream()
- The main features of flow
- 2. The steps to use stream
- step:
- 3. Common intermediate operations and terminal operations
- Intermediate operation
- Terminal operation
- Four. Example
1. What is stream()
Stream
The API provides a high-level abstraction that allows us to convert sets into a streaming processing mode, allowing us to perform a series of operations in a large chain manner.
Simply put: it is to turn the collection into a stream, so that we can continuously perform the operations we want on this stream
The main features of flow
-
No data stored: Streams will not change the original data structure, they only provide one inData Sourcemethod to perform an operation.
-
Functional operations: The flow operation is usuallyfunctionIt means you can pass itlambda expressionOr method reference to perform an operation.
-
Lazy evaluation: The intermediate operation of the stream will not be executed immediately, and will only be executed when a terminal operation is encountered. This means that the intermediate operation will form aassembly line, only start computing when the result is really needed, which helps optimize performance, especially when dealing with big data or complex operational chains.
-
Can be parallel: Streams can be easily processed in parallel, using multi-core processors to improveperformance, just need to
stream()
Replace the method withparallelStream()
method.
2. The steps to use stream
Stream
Operations are divided intoIntermediate operation
andTerminal operation
The intermediate operation returns aStream
, allowing multiple operations to be performed continuously
Terminal operations will output a result or produce a side effect.
step:
-
create
Stream
:- Created from data sources such as collections or arrays
Stream
。 - use
Stream
static methods of the class, such as。
- Created from data sources such as collections or arrays
-
Perform intermediate operations:
- Intermediate operation as
filter
,map
,sorted
Wait, each operation will return a new oneStream
Object, other intermediate operations can be continued.
- Intermediate operation as
-
Perform terminal operations:
- Terminal operation as
forEach
,collect
,reduce
Then, these operations will be closedStream
And generate results.
- Terminal operation as
3. Common intermediate operations and terminal operations
Intermediate operation
The intermediate operation returns anotherStream
, further operation is allowed.
-
filter(Predicate<T>)
:
Filter elements in the stream. Only elements that match the given predicate.list.stream().filter(x -> x > 10) // Filter out elements larger than 10
- 1
-
map(Function<T, R>)
:
Convert each element in the stream into another form and apply to each element through the given function.list.stream().map(x -> x * x) // Replace each element with its square
- 1
-
flatMap(Function<T, Stream<R>>)
:
andmap
Similar, but each input element can be mapped to multiple output elements (i.e., a list of elements).list.stream().flatMap(x -> Stream.of(x, x + 1)) // Convert each element to multiple elements
- 1
-
sorted()
andsorted(Comparator<T>)
:
Order elements in the stream naturally or use a custom comparator.list.stream().sorted() // Natural sorting list.stream().sorted(Comparator.reverseOrder()) // Inverse order
- 1
- 2
-
distinct()
:
Returns a stream containing unique elements (according to(Object)
Method to remove heavy weight).list.stream().distinct()
- 1
-
limit(long n)
andskip(long n)
:limit
Intercept the first n elements of the stream;skip
Skip the first n elements.list.stream().limit(5) // Take the first 5 elements list.stream().skip(5) // Skip the first 5 elements
- 1
- 2
Terminal operation
Terminal operations generate results from the stream's pipeline.
-
forEach(Consumer<T>)
:
Perform the given action on each element.list.stream().forEach(System.out::println) // Print each element
- 1
-
collect(Collector<T, A, R>)
:
Converting streams to other forms is a very powerful operation, especiallyCollectors
Classes provide many convenient methods.List<Integer> newList = list.stream().collect(Collectors.toList()); // Collected List
- 1
-
reduce(BinaryOperator<T>)
:
By reusing the given operation, combine elements in the stream and return aOptional
。Optional<Integer> sum = list.stream().reduce(Integer::sum); //Sum
- 1
-
anyMatch(Predicate<T>)
,allMatch(Predicate<T>)
,noneMatch(Predicate<T>)
:
Check if there is at least one element in the stream (anyMatch
), all elements (allMatch
), no elements (noneMatch
) Match the given predicate.boolean hasEven = list.stream().anyMatch(x -> x % 2 == 0); // Check if there are even numbers
- 1
-
count()
:
Returns the number of elements in the stream.long count = list.stream().count();
- 1
-
min(Comparator<T>)
andmax(Comparator<T>)
:
Returns the minimum or maximum value in the stream according to the given comparator.Optional<Integer> min = list.stream().min(Integer::compare); Optional<Integer> max = list.stream().max(Integer::compare);
- 1
- 2
Four. Example
List<Employee> employees = getEmployees(); // Assume this is a list of employees taken from the database or elsewhere
List<Employee> filteredEmployees = employees.stream() // Create Stream
.filter(e -> e.getAge() > 30) // Filter age
.sorted(Comparator.comparing(Employee::getName)) // Sort by name
.collect(Collectors.toList()); // Collect new list
- 1
- 2
- 3
- 4
- 5
- 6