迭代时在Java8中修改流内的对象 [英] Modifying Objects within stream in Java8 while iterating
问题描述
在Java8流中,我可以修改/更新其中的对象吗?
例如。 列表<使用者>用户
:
In Java8 streams, am I allowed to modify/update objects within?
For eg. List<User> users
:
users.stream().forEach(u -> u.setProperty("value"))
推荐答案
是的,你可以修改状态流中的对象,但您应该避免修改流的 源 的状态。来自不干涉流包文档的一部分,我们可以读到:
Yes, you can modify state of objects inside your stream, but you should avoid modifying state of source of stream. From non-interference section of stream package documentation we can read that:
对于大多数数据源,防止干扰意味着确保数据源是在流管道执行期间未完全修改。值得注意的例外是其源是并发集合的流,这些集合专门用于处理并发修改。并发流源是
Spliterator
报告CONCURRENT
特征的源。
For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose
Spliterator
reports theCONCURRENT
characteristic.
所以这没关系
List<User> users = getUsers();
users.stream().forEach(u -> u.setProperty(value));
但是
users.stream().forEach(u -> users.remove(u));
不是,可能会抛出 ConcurrentModificationException
或其他像NPE这样的例外:
is not and may throw ConcurrentModificationException
or other exceptions like NPE:
List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
list.stream()
.filter(i -> i > 5)
.forEach(i -> list.remove(i)); //throws NullPointerException
这篇关于迭代时在Java8中修改流内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!