Does Stream.sorted (). Does ForEach () work as intended?

While working on a Java project, I came across code that looked like this:

someMap.keySet().stream().sorted().forEach(/* ... */);

The goal is to do something for each key on the map in accordance with the natural order of the keys, and this is similar to what happens in practice. However, I am not sure if this behavior is guaranteed. Javadoc for Stream # forEach says:

The behavior of this operation is clearly non-deterministic. For parallel stream pipelines, this operation does not guarantee respect for the order in which the stream is called, since it will benefit parallelism. For any given element, an action can be performed at any time and in any thread that the library selects.

I know that if the code used .parallelStream()instead .stream(), that it will not be guaranteed to work, but since it uses a serial stream (of which Javadoc does not say anything), I am not sure. Is it always guaranteed, or should this code use .forEachOrdered()instead .forEach()for this?

EDIT: I believe this question is not a duplicate of forEach vs forEachOrdered in Java 8 Stream , because this question asks the question: “What is an example of the difference between forEach and forEachOrdered in general”, and the accepted answer is mostly “parallel streams”. This question relates, in particular, to sequential threads.

+4
source share
3 answers

, forEach , " ". .

forEachOrdered , , .

forEach forEachOrdered , .

, , forEach , java- , forEachOrdered, .

+7

- , , . , , , , :

Stream.of(5, 4, 3, 1)
      .unordered()
      .forEach(System.out::println);

, - , .

, , ,

+3

, .forEachOdered() .forEach() ?

. , . javadoc, forEach() . , , , -.

, , javadoc . , .forEachOrdered() .


So ... I would point out this error to the supporters of this application. We cannot predict that it will break in the future, but it certainly can. Hidden errors are errors.

0
source

Source: https://habr.com/ru/post/1691569/


All Articles