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

This is an example: code A:

files.forEach(f -> {
    //TODO
});

and another code B can be used as follows:

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

What is the difference between them, with stream()and no stream()?

+4
source share
4 answers

Practically speaking, they are basically the same, but there is a slight semantic difference.

Code A is defined Iterable.forEach, while code B is determined Stream.forEach. The definition Stream.forEachallows you to process elements in any order - even for sequential threads. (For parallel threads Stream.forEach, it will most likely handle elements out of order.)

Iterable.forEach forEachRemaining(). , (JDK 8) Stream.forEach Spliterator, , forEachRemaining Iterator - , Iterable.forEach . , , .

, , .

( , forEachOrdered().)

+12

, stream, , .

+3

(, ) . . , ,

(map, skip, concat, substream, different, filter, sorted, limit, peek..), java.util.stream.Stream, - , .

(forEach, max, count, matchAny, findFirst, , , , findAny) , .

Basically, it looks like a pipeline, as in Unix.

0
source

Both approaches use a terminal operation Iterable.forEach, but version c .stream()also unnecessarily creates an object Streamrepresenting the list. Although there is no difference, it is suboptimal.

-1
source

All Articles