java - What is difference between Collection.stream().forEach() and Collection.forEach()? -


i understand .stream(), can use chain operations .filter() or use parallel stream. difference between them if need execute small operations (for example, printing elements of list)?

collection.stream().foreach(system.out::println); collection.foreach(system.out::println); 

for simple cases such 1 illustrated, same. however, there number of subtle differences might significant.

one issue ordering. stream.foreach, order undefined. it's unlikely occur sequential streams, still, it's within specification stream.foreach execute in arbitrary order. occur in parallel streams. contrast, iterable.foreach executed in iteration order of iterable, if 1 specified.

another issue side effects. action specified in stream.foreach required non-interfering. (see java.util.stream package doc.) iterable.foreach potentially has fewer restrictions. collections in java.util, iterable.foreach use collection's iterator, of designed fail-fast , throw concurrentmodificationexception if collection structurally modified during iteration. however, modifications aren't structural are allowed during iteration. example, arraylist class documentation says "merely setting value of element not structural modification." thus, action arraylist.foreach allowed set values in underlying arraylist without problems.

the concurrent collections yet again different. instead of fail-fast, designed weakly consistent. full definition @ link. briefly, though, consider concurrentlinkeddeque. action passed foreach method is allowed modify underlying deque, structurally, , concurrentmodificationexception never thrown. however, modification occurs might or might not visible in iteration. (hence "weak" consistency.)

still difference visible if iterable.foreach iterating on synchronized collection. on such collection, iterable.foreach takes collection's lock once , holds across calls action method. stream.foreach call uses collection's spliterator, not lock, , relies on prevailing rule of non-interference. collection backing stream modified during iteration, , if is, concurrentmodificationexception or inconsistent behavior result.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -