How it works...

There are Stream objects that may have an encounter order depending on its source and the intermediate operations you have applied before. This encounter order imposes a restriction about the order in which the elements must be processed by certain methods. For example, if you use the limit() or skip() methods in Stream with an encounter order, they will get and ignore the first elements according to that encounter order. There are other operations, such as the forEach() method, that don't take into account the encounter order. If you apply the same operations to a stream with an encounter order, the result will always be the same. If the stream doesn't have an encounter order, the results may vary.

When you work with sequential streams, the encounter order doesn't have any impact on the performance of the application, but with parallel streams it can affect it greatly. Depending on the operations, it would be necessary to process more than once the elements of Stream or to store in a buffer a big amount of data. In this case, removing the encounter order using the unordered() method, as we did in this recipe, will significantly increase the performance of the application.

On the other hand, the sorted() method sorts the elements of the Stream. If you use this method, the elements of Stream must implement the Comparable interface. Otherwise, you can pass a Comparator as a parameter that will be used to sort the elements. If you use this method, you are creating an ordered stream, so all the things explained before to the streams with an encounter order are applicable to the resultant stream.

Finally, the forEach() method doesn't take into account the encounter order of the stream. If you want to take this encounter order into account, say, to write the elements of the stream order after sorting them, you can use the forEachOrdered() method.

The following screenshot shows part of the output of the example:

You can see that when you call the limit(1) method in the parallel stream generated from TreeSet, you always obtain the same result because the Stream API respects the encounter order of that structure. But when we include a call to the unordered() method, the encounter order is not taken into account and the result obtained should vary, as in this case.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.34.224