java - What is the difference between .foreach and .stream().foreach? -


this example: code a:

files.foreach(f -> {     //todo }); 

and code b may use on way:

files.stream().foreach(f -> { }); 

what difference between both, stream() , no stream()?

practically speaking, same, there small semantic difference.

code defined iterable.foreach, whereas code b defined stream.foreach. definition of stream.foreach allows elements processed in order -- sequential streams. (for parallel streams, stream.foreach process elements out-of-order.)

iterable.foreach gets iterator source , calls foreachremaining() on it. far can see, current (jdk 8) implementations of stream.foreach on collections classes create spliterator built 1 of source's iterators, , call foreachremaining on iterator -- iterable.foreach does. same thing, though streams version has setup overhead.

however, in future, it's possible streams implementation change no longer case.

(if want guarantee ordering of processing streams elements, use foreachordered() instead.)


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -