Detailed explanation of Stream in Java

Today in Java learning, I encountered the operation method of starm. After understanding it, I found that many operations are very practical and are often used in project development. I wrote this blog for recording.

1. Basic concept of Stream

Stream is a new API introduced in Java 8, which can greatly facilitate our continuous operations on data sources such as collections and arrays. It simplifies our code and makes it easier to maintain and understand. Stream is actually a lazy calculation method, and the calculation will only start when the output result is needed.

Lazy Computation in Stream Operations

Stream is only an operation method for the original data, and the data itself has not changed. Therefore, when operating on Stream, the operation instruction is actuallystored in the operation streamis not calculated and executed, and will not be triggered until the output result is required. This method can reduce the amount of calculation and overhead, and improve efficiency.

Create Stream

Streams can be created from many kinds of data sources, such as List, Set or any other class that implements the Iterable interface. The creation method is very simple, just use the stream()or parallelStream()method.

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream(); // 串行Stream
Stream<String> parallelStream = list.parallelStream(); // 并行Stream

2. Commonly used Stream operation methods

Commonly used Stream operations include: filtering, mapping, sorting, deduplication, counting, reduction, etc.

filter

The filter method filteris used to filter the elements in the Streamfilter, keeping only elements that meet the specified criteria. Its functional interface is Predicate<T>, and its method is boolean test(T t), accepting an object of type T and returning a booleantype value. When the method returns true, the element meets the conditions and will be kept in the Stream.

For example the following code:

List<String> list = Arrays.asList("apple", "banana", "orange", "pear");
Stream<String> stream = list.stream().filter(s -> s.length() > 5);

The lamdba expression in it s -> s.length() > 5is used to filter strings whose length is greater than 5.

map

The mapping method mapis used to map the elements in the Stream according to the specified rulesconvert. Its functional interface is Function<T, R>, and its method is R apply(T t), which accepts an object of type T and returns an object of type R. In essence, the map method is to make a mapping of the same type to each element in the Stream.

For example the following code:

List<String> list = Arrays.asList("apple", "banana", "orange", "pear");
Stream<Integer> stream = list.stream().map(String::length);

The method references in it String::lengthare used to convert each string object to its length value.

sorted

The sort method sortedis used to sort the elements in the Streamto sort. Its functional interface is Comparator<T>, and its method is int compare(T o1, T o2), accepting two objects of type T and returning a inttype value. When the return value is negative, it indicates that o1 should be arranged in front of o2; when the return value is positive, it indicates that o1 should be arranged behind o2; when the return value is 0, it indicates that the order of o1 and o2 is uncertain.

For example the following code:

List<String> list = Arrays.asList("apple", "banana", "orange", "pear");
Stream<String> stream = list.stream().sorted();

Among them, Stream will use the default collation to sort the elements.

distinct

The deduplication method distinctis used to convert the stream inDuplicate element removal, keep only one. It uses the equals method for comparison, so it is necessary to ensure that the elements in the data source correctly implement the equals method.

For example the following code:

List<String> list = Arrays.asList("apple", "banana", "orange", "banana");
Stream<String> stream = list.stream().distinct();

Among them, the element "banana" in the Stream appears twice, but after calling the distinct method, only the "banana" element is retained once.

count

count method countforReturns the number of elements in the Stream, the return value longtype.

For example the following code:

List<String> list = Arrays.asList("apple", "banana", "orange", "pear");
long count = list.stream().count();

Among them, the value returned by the count method is 4, which is the number of elements in the Stream.

reduce

The reduce method reduceis used to reduce the elements in the Stream to a value. Its functional interface is BinaryOperator<T>, and its method is apply(T t1, T t2), which is used to reduce two T-type values ​​and return a T-type value. The reduce method accepts two parameters: the first parameter represents the initial value of the reduction operation, which can be any type of object; the second parameter is an object of type BinaryOperator, which is used to recursively reduce all elements in the Stream .

For example the following code:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream().reduce(0, Integer::sum);

forEach

forEachThe method is used to perform the specified operation on each element in the Stream, and its functional interface is Consumer<T>, and its method is void accept(T t). forEachIt is a terminal operation, which can only be performed once for the same Stream. Once the terminal operation is performed, the Stream cannot be reused.

For example the following code:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.stream().forEach(System.out::println);

Among them, the collection is first streamconverted into a Stream stream through the method, and then forEacheach integer is output using the method, and the final output result is:

1
2
3
4
5

3. Summary

Stream is a very important API in Java 8, which can greatly facilitate our continuous operations on data sources such as lists and collections. Stream operations can greatly simplify our code and improve efficiency, so we should be proficient in using Stream in Java programming. It should be noted that when operating on Stream, you should pay attention to the lazy calculation feature of Stream to avoid unnecessary calculation overhead.

Guess you like

Origin blog.csdn.net/weixin_52357829/article/details/131177398