Matching by ordered list in java 8

The Java 8 streaming library provides the forEachOrdered API , the documentation of which is reproduced here

void forEachOrdered (user action)

Performs an action for each element of this stream.

This is a terminal operation.

This operation processes the elements one at a time, in order of execution, if one exists . The execution of an action for one element occurs - before the execution of the action for subsequent elements , but for any given element, the action can be performed in any thread that the library selects.

Do we have any guarantees regarding the order of the API maps ?

For example, I have code in code

private final BazUtils bazUtils;

public List<Foo> getFoos(List<Bar> bars) {
    AtomicInteger idx = new AtomicInteger(1);
    return bars.stream()
        .map(bar -> bazUtils.getFoo(bar, idx.getAndAdd(1)))
        .collect(Collectors.toList());
}

bars ?

+1
2

. , " " " ":

... , , visibility - , , . , . , (, IntStream.range(0,5).parallel().map(x -> x*2).toArray() [0, 2, 4, 6, 8]), , -

, , AtomicInteger, . , .. List s Bar List, int, , ( , ).

forEachOrdered , . .

, ,

public List<Foo> getFoos(List<Bar> bars) {
    return IntStream.range(0, bars.size()) //you may add .parallel()
        .mapToObj(idx -> bazUtils.getFoo(bars.get(idx), idx+1))
        .collect(Collectors.toList());
}
+2

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps

, ; , [1, 2, 3], (x → x * 2) [2, 4, 6]. , , [2, 4, 6] .

, ; map.

+3

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


All Articles