为什么最后有 close() 时嵌套流不处理 map 或 filter 函数
Why the nested stream not processing map or filter functions when there is close() in the end
我有一个嵌套流,我正在使用它来处理与需求相关的一些数据
final Map<String, Long> productModelQuantityReturnedMap = new HashMap<>();
sampleList.stream()
.map(sampleModel -> {
sampleModel.getEntries()
.stream()
.filter(entryModel -> Objects.nonNull(entryModel.getOrderEntry()))
.map(returnEntryModel -> {
sampleMap.put(
key,
val);
return null;
}).close();
return null;
}).close();
是的,我知道使用 for each 或 for 是理想的,但是是的。我想将其扩展到一个并行线程,因为它有很多相互不依赖的数据点。
虽然它说流或并行流将等到内部部分完成,但它直接进入外部流的 close()
,我不明白为什么。
有人可以帮我找到这里的问题吗?
map
和 filter
是中间操作。除非调用终端操作,否则不会处理流。在您的代码中,您没有调用任何终端操作来处理流。由于 close
是 而不是 终端操作,因此它不处理流。它只是重置所有内容并结束流。您可以参考 AbstractPipeline
查看 close
的源代码。唯一被执行的是使用 onClose
方法传递的代码(如果有的话)。 (即,如果您在流中使用 onClose
,则 stream().onClose(() -> myCloseAction())....
)。
此外,close
在您发布的代码中并不是真正需要的。正如您在问题本身中提到的,您可以使用 forEach
。它肯定也适用于并行流 (forEach)。唯一的问题是您的代码似乎正在更新地图。确保这是并发映射。或者最好使用 Collectors
class 中的 toMap
或 toConcurrentMap
而不是使用 forEach
.
将元素放入地图中
我有一个嵌套流,我正在使用它来处理与需求相关的一些数据
final Map<String, Long> productModelQuantityReturnedMap = new HashMap<>();
sampleList.stream()
.map(sampleModel -> {
sampleModel.getEntries()
.stream()
.filter(entryModel -> Objects.nonNull(entryModel.getOrderEntry()))
.map(returnEntryModel -> {
sampleMap.put(
key,
val);
return null;
}).close();
return null;
}).close();
是的,我知道使用 for each 或 for 是理想的,但是是的。我想将其扩展到一个并行线程,因为它有很多相互不依赖的数据点。
虽然它说流或并行流将等到内部部分完成,但它直接进入外部流的 close()
,我不明白为什么。
有人可以帮我找到这里的问题吗?
map
和 filter
是中间操作。除非调用终端操作,否则不会处理流。在您的代码中,您没有调用任何终端操作来处理流。由于 close
是 而不是 终端操作,因此它不处理流。它只是重置所有内容并结束流。您可以参考 AbstractPipeline
查看 close
的源代码。唯一被执行的是使用 onClose
方法传递的代码(如果有的话)。 (即,如果您在流中使用 onClose
,则 stream().onClose(() -> myCloseAction())....
)。
此外,close
在您发布的代码中并不是真正需要的。正如您在问题本身中提到的,您可以使用 forEach
。它肯定也适用于并行流 (forEach)。唯一的问题是您的代码似乎正在更新地图。确保这是并发映射。或者最好使用 Collectors
class 中的 toMap
或 toConcurrentMap
而不是使用 forEach
.