About the pitfalls encountered when using streams in java8

Java 8 adds stream processing, which provides many methods for various operations on the list. Everyone who has used it knows that it is extremely convenient. Such as filtering, sorting, merging, type conversion, etc. The following are the pitfalls that I have encountered in my actual work. I have recorded them to avoid others stepping on them.

The first pitfall: Collectors.toAsList() actually creates a new list and assigns values ​​to it.

 

 

 

Pay attention to the way Collectors.toList() is written here. This is actually the underlying new ArraryList(). The filtered data is put into a new list. Although the variables marked 1 and 2 are the same variable, the memory addresses are different. The following logic deletes certain elements in hldrPolVOList. But after this method is executed, the elements inside are not actually deleted. The reason is that new ArraryList() here changes the memory address.

test:

Solution:

The second pitfall: list.stream().foreach(p->{return;}); the return here is the ending foreach rather than the external method

 

 

Solution: Change the stream into a for loop.

 

 

The third pitfall; in the foreach operation of parallel stream (parallelStream()), if the values ​​in one ArrayList are copied to another ArrayList, there may be more or less elements. The reason is that parallel streams are multi-threaded, while ArrayList is not thread-safe.

 

 

 

Written at the end: java8's stream is very easy to use. The main code is more concise and does not require writing a lot of code. However, it is not suitable for all scenarios. If the business originally takes a long time, then there is hope to reduce the business execution time. When the amount of data is not very large, stream flow has no advantage, that is to say, the amount of data is small, and it is agreed to use stream to process data in many places in the business. At this time, the execution time is more than that of the for loop, and only the business volume reaches The advantage is only reflected at the million level.

Guess you like

Origin blog.csdn.net/dhklsl/article/details/117918739