gpt4 book ai didi

Java 8 Stream - 排序方法的执行标准与过滤器和映射方法不同

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:40:24 24 4
gpt4 key购买 nike

这个问题与 Java 8 Stream - Filter and foreach method not printing as expected 有某种关系

我正在使用 Java 8 Stream 的排序、过滤和映射方法。牢记过滤器和 map 如何按照上述问题的答案中的规定工作,我尝试了如下排序方法:

Stream.of("d2", "a2", "b1", "b3", "c")
.sorted((s1, s2) -> {
System.out.printf("sort: %s; %s\n", s1, s2);
return s1.compareTo(s2);
})
.filter(s -> {
System.out.println("filter: " + s);
return s.startsWith("a");
})
.map(s -> {
System.out.println("map: " + s);
return s.toUpperCase();
})
.forEach(s -> System.out.println("forEach: " + s));

我得到的输出是:

sort: a2; d2 sort: b1; a2 sort: b1; d2 sort: b1; a2 sort: b3; b1 sort: b3; d2 sort: c; b3 sort: c; d2 filter: a2 map: a2 forEach: A2 filter: b1 filter: b3 filter: c filter: d2

也就是说,现在对整个循环执行排序方法,然后对单个项执行过滤和映射函数。由于这三个都是中间函数,因此它们的工作方式应该相同。执行令好不好?我没有明白我做错了什么。

最佳答案

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

Side-effects

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

[...] Further, the ordering of those effects may be surprising. Even when a pipeline is constrained to produce a result that is consistent with the encounter order of the stream source (for example, IntStream.range(0,5).parallel().map(x -> x*2).toArray() must produce [0, 2, 4, 6, 8]), no guarantees are made as to the order in which the mapper function is applied to individual elements, or in what thread any behavioral parameter is executed for a given element.

enter image description here

关于Java 8 Stream - 排序方法的执行标准与过滤器和映射方法不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40864416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com