Complete analysis of the usage of Stream streams in Java
In Java programming, Stream streams provide an efficient and convenient way to process collection data. It allows us to perform various operations on data in a declarative manner, such as filtering, mapping, sorting, aggregation, etc., greatly simplifying the code writing of data processing. This article will introduce in detail the usage of Stream streams in Java, including basic usage, intermediate usage, advanced usage and some special methods.
1. Basic usage
1. Create Stream
- Create Stream from a collection: by calling the collection's
stream()
Methods can create a sequential stream. For example:
List<String> list = ("apple", "banana", "cherry"); Stream<String> stream1 = ();
- Create Stream from an array: Use
()
Methods can create streams from arrays. For example:
String[] array = {"apple", "banana", "cherry"}; Stream<String> stream2 = (array);
2. Intermediate operation
- filter: filter element: use
filter
Methods can filter elements in the stream according to specified conditions. For example, the following code filters out strings starting with "a":
() .filter(s -> ("a")) .forEach(::println); // Output: apple
- map: Convert elements:
map
Methods can convert each element in the stream according to the specified function. For example, convert a string to uppercase:
() .map(String::toUpperCase) .forEach(::println); // Output: APPLE BANANA CHERRY
3. Terminate the operation
- forEach: traversal elements:
forEach
Methods are used to traverse each element in the stream and perform the specified operation. For example:
().forEach(::println);
- collect: Collect the results to the collection:
collect
Methods can collect elements in the stream into a specified collection. For example, collect strings with lengths greater than 5 into a new list:
List<String> result1 = () .filter(s -> () > 5) .collect(()); // Or use the toList() method (Java 16 and above)List<String> result2 = () .filter(s -> () > 5) .toList();
2. Intermediate usage
1. Sort
- sorted: natural sort or custom sort:
sorted
Methods can sort elements in the stream. If the element is implementedComparable
Interface, you can use parameters without parameters directlysorted
Methods are sorted naturally. For example:
() .sorted() .forEach(::println); // Output: apple banana cherry
If you need to customize the sorting rules, you can pass in oneComparator
Comparator. For example, sort in reverse order by string length:
() .sorted(()) .forEach(::println); // Output: cherry banana apple
2. Get rid of the heavy
usedistinct
Methods can remove duplicate elements in the stream. For example:
List<Integer> numbers = (1, 2, 2, 3, 4, 4, 5); List<Integer> distinctNumbers = () .distinct() .toList();
3. Aggregation operation
- reduce: Reduce operation:
reduce
The method can reduce elements in the stream, such as summing, product, etc. For example, calculate the sum of the integer list:
Optional<Integer> sum = () .reduce((a, b) -> a + b); // Can be replaced with .reduce(Integer::sum);(()); // Output: 19
3. Advanced usage
1. Parallel flow
- parallelStream: parallel processing (improving efficiency): use
parallelStream
Methods can create a parallel stream that will process elements in the stream in parallel on multiple threads, improving processing efficiency. For example, calculate the number of elements that meet the criteria:
long count = () .filter(s -> () > 5) .count();
2. Short circuit operation
- anyMatch, allMatch, noneMatch: Short-circuit matching: These methods are used to perform short-circuit matching operations in the stream.
-
anyMatch
: Return as long as there is an element in the stream that meets the conditiontrue
. For example:
-
boolean anyStartsWithA = () .anyMatch(s -> ("a")); (anyStartsWithA); // Output: true
-
allMatch
: Return only if all elements in the stream meet the conditionstrue
. For example:
boolean allStartsWithA = () .allMatch(s -> ("a")); (allStartsWithA); // Output: false
-
noneMatch
: If no element in the stream meets the condition, returntrue
. For example:
boolean noneStartsWithZ = () .noneMatch(s -> ("z")); (noneStartsWithZ); // Output: true
3. Grouping and Partitioning
- : Grouping: Use
groupingBy
Methods can group elements in a stream into one according to the specified classification function.Map
middle. For example, group by the initial letter of a string:
Map<Character, List<String>> groupedByFirstLetter = () .collect((s -> (0))); (groupedByFirstLetter); // {a=[apple], b=[banana], c=[cherry]}
- : Partition:
partitioningBy
Method partitions elements in the stream into one according to the specified boolean conditionsMap
Medium, the key istrue
andfalse
. For example, partition based on whether the string length is greater than 5:
Map<Boolean, List<String>> partitioned = () .collect((s -> () > 5)); // {false=[apple], true=[banana, cherry]} (partitioned);
4. Collect Map
- : Collected Map: Use
toMap
Methods can collect elements in the stream into oneMap
In , you need to specify the mapping function of key and value. For example:
Map<String, Integer> map = () .collect(((), String::length)); (map);
4. FlatMap usage
flatMap
The method is used to convert each element in the stream into another stream, and then flatten those streams into a single stream. This is very useful when dealing with nested collections. For example:
List<List<String>> listOfLists = ( ("apple", "banana"), ("cherry", "date"), ("fig", "grape") ); // Flatten nested lists using flatMapList<String> flattenedList = () .flatMap(List::stream) .collect(()); (flattenedList); // Output: [apple, banana, cherry, date, fig, grape]
5. Peek usage
-
peek
Methods are mainly used for debugging, which allows you to perform an operation (such as printing) on each element of the stream without changing the elements in the stream.peek
Returns a new stream containing the same elements as the original stream. For example:
List<String> list = ("apple", "banana", "cherry"); List<String> result = () .peek(s -> ("Processing: " + s)) // Print each element .map(String::toUpperCase) .collect(()); (result); // Output: [APPLE, BANANA, CHERRY]
6. Limit usage
-
limit
Methods are used to limit the number of elements in the stream. For example:
List<String> list = ("apple", "banana", "cherry", "date", "fig", "grape"); List<String> limitedList = () .limit(3) .collect(()); (limitedList); // Output: [apple, banana, cherry]
7. Skip usage
-
skip
Method is used to skip the front in the flown
Element. For example:
List<String> list = ("apple", "banana", "cherry", "date", "fig", "grape"); List<String> skippedList = () .skip(3) .collect(()); (skippedList); // Output: [date, fig, grape]
8. Min and max
-
min
andmax
Methods are used to find the minimum and maximum values in a stream. For example:
List<Integer> numbers = (10, 20, 30, 40, 50); // Find the minimum valueOptional<Integer> min = () .min(Integer::compareTo); (()); // Output: 10// Find the maximum valueOptional<Integer> max = () .max(Integer::compareTo); (()); // Output: 50
9. findAny and findFirst
-
findAny
andfindFirst
Methods are used to find any element and the first element in the stream. For example:
List<String> list = ("apple", "banana", "cherry"); // Find any elementOptional<String> anyElement = ().findAny(); (()); // Output: apple (or banana or cherry)// Find the first elementOptional<String> firstElement = ().findFirst(); (()); // Output: apple
Through the above comprehensive introduction to Stream streams in Java, we can see that it provides powerful and flexible capabilities in data processing. The rational use of Stream streams can make our code more concise and efficient, improving programming efficiency and code readability. In actual development, choosing the appropriate Stream stream operation method according to specific needs can better process the collection data and implement complex data processing logic.
This is the article about the most Java Stream streaming method. For more related Java Stream content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!