Reputation: 1531
Does filter
chaining change the outcome if i use parallelStream()
instead of stream()
?
I tried with a few thousand records, and the output appeared consistent over a few iterations. But since this involves threads,(and I could not find enough relevant material that talks about this combination) I want to make doubly sure that parallel stream does not impact the output of filter chaining in any way. Example code:
List<Element> list = myList.parallelStream()
.filter(element -> element.getId() > 10)
.filter(element -> element.getName().contains("something"))
.collect(Collectors.toList());
Upvotes: 2
Views: 3836
Reputation: 31968
Short answer: No.
The filter
operation as documented expects a non-interferening and stateless predicate to apply to each element to determine if it should be included as part of the new stream.
Few aspects that you shall consider for that are -
myList
in the existing code to be) -For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline.
myList
and its element
s within your filter operations are not mutated)Note also that attempting to access mutable state from behavioral parameters presents you with a bad choice with respect to safety and performance;
Moreover, think around it, what is it in your filter
operation that would be impacted by multiple threads. Given the current code, nothing functionally, as long as both the operations are executed, you would get a consistent result regardless of the thread(s) executing them.
Upvotes: 2