Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working.
Collection.stream().forEach() is basically used for iteration in a group of objects by converting a collection into the stream and then iterate over the stream of collection. While iterating over the collection, if any structural changes are made to collections, then it will throw the concurrent modification exception.
Collection.forEach() uses the collection’s iterator(whichever is specified). The majority of the collections do not allow modifications in the structure while iterating over that collection. If any changes happen to that collection, i.e. addition of an element or the removal of the element, then they will throw the concurrent modification error. If collection.forEach() is iterating over a synchronized collection, then they will lock the segment of collection and hold it over all the calls that can be made w.r.t to that collection.
Difference Between Collection.stream().forEach() and Collection.forEach()
|Collection.stream().forEach() is also used for iterating the collection but it first converts the collection to the stream and then iterates over the stream of collection.||Collection.forEach() uses the collections iterator.|
|Unlike Collection.forEach() it does not execute in any specific order, i.e. the order is not defined.||If always execute in the iteration order of iterable, if one is specified.|
|During structure modification in the collection, the exception will be thrown later.||If we perform any structural modification in the collection by using the collection.forEach() it will immediately throw an exception.|
|If iteration is happening over the synchronized collection, then it does not lock the collection.||If iteration is happening over the synchronized collection, then it locks the collection and holds it across all the calls.|
Below is a Java program to show the usage of the Collection.stream.forEach():
Below is a Java program to show the usage of Collection.forEach() Method:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.