I\'m trying to understand warnings I found in the Documentation on Streams. I\'ve gotten in the habit of using forEach() as a general purpose iterator. And that\'s lead me t
I believe the documentation is mentioning about the side effects demonstrated by the below code:
List matched = new ArrayList<>();
List elements = new ArrayList<>();
for(int i=0 ; i< 10000 ; i++) {
elements.add(i);
}
elements.parallelStream()
.forEach(e -> {
if(e >= 100) {
matched.add(e);
}
});
System.out.println(matched.size());
This code streams through the list in parallel, and tries to add elements into other list if they match the certain criteria. As the resultant list is not synchronised, you will get java.lang.ArrayIndexOutOfBoundsException while executing the above code.
The fix would be to create a new list and return, e.g.:
List elements = new ArrayList<>();
for(int i=0 ; i< 10000 ; i++) {
elements.add(i);
}
List matched = elements.parallelStream()
.filter(e -> e >= 100)
.collect(Collectors.toList());
System.out.println(matched.size());