gpt4 book ai didi

java - 将流分配给变量 : Okay or Not?

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

如果我将一个流分配给一个变量,例如

final Stream<String> docs = REST_CLIENT.postLS(RestClient.appendSegmentToPath(bucketUrl, "_bulk_get"),

这会是个坏主意吗?因为流需要将数据存储在内存中——就像 Collection 一样。但与集合不同,流不指定如何存储数据 - 作为数组、树或其他

最佳答案

流是延迟计算的,它们不像充当数据持有者的集合。所以在你的代码中 Stream<String>String 的来源数据,当您执行流操作并进行终端操作时,流管道将被评估并被称为消耗,直到那时没有内存用于存储来自流源的数据。

这是根据 Java docs :

Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

Collections and streams, while bearing some superficial similarities, have different goals. Collections are primarily concerned with the efficient management of, and access to, their elements. By contrast, streams do not provide a means to directly access or manipulate their elements, and are instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source.

但是一旦您对 Stream 使用了终端操作,Stream 就会被消耗掉并且不能再次使用。您需要从您的来源获取新的 Stream 才能执行相同的操作。

例如让我们得到一个Stream<String>并将其引用保存在变量中:

Stream<String> stream  = Stream.of("foo", "bar");
stream.forEach(System.out::println); //invoke terminal operation
stream.forEach(System.out::println); // stream is already consumed

当您尝试再次调用终端操作时,您会得到一个 java.lang.IllegalStateException: stream has already been operated upon or closed

关于java - 将流分配给变量 : Okay or Not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57951697/

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