Use of stream in List

Stream in Java is an abstract concept for processing collection data. It allows us to operate on collections in a way similar to SQL queries, such as filtering, mapping, sorting, aggregation, etc. Stream allows us to process and convert collections in a more concise way, while also providing more efficient parallel processing capabilities.

For the List collection, we can obtain a Stream by calling the stream() method, and then use various Stream operation methods to process the elements in it. For example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// 过滤出大于3的元素
Stream<Integer> stream = numbers.stream().filter(n -> n > 3);

// 对每个元素进行平方操作
Stream<Integer> squaredStream = numbers.stream().map(n -> n * n);

// 对所有元素求和
int sum = numbers.stream().reduce(0, (a, b) -> a + b);

In the above code, filter() method can filter out elements greater than 3, map() method can perform square operation on each element, The reduce() method can sum all elements.

Stream operations can be called in a chain and will not modify the original collection, but return a new Stream. This method allows us to perform multiple operations on the collection in a pipelined manner, which can improve the readability and simplicity of the code.

It should be noted that the Stream stream is executed lazily, that is, before the termination operation (such as forEach(), collect(), etc.) is called, the intermediate operation ( For example, filter(), map(), etc.) will not be actually executed and will only generate a new Stream. This avoids unnecessary computation and memory consumption.

Guess you like

Origin blog.csdn.net/Flying_Fish_roe/article/details/135018199