Modifying Objects within stream in Java8 while iterating(迭代时在Java8中修改流中的对象)
问题描述
在 Java8 流中,我可以修改/更新其中的对象吗?例如.列表<用户>用户
:
In Java8 streams, am I allowed to modify/update objects within?
For eg. List<User> users
:
users.stream().forEach(u -> u.setProperty("value"))
推荐答案
是的,您可以修改流中对象的状态,但通常您应该避免修改 source 的流.来自 无干扰 流包文档的部分我们可以阅读:
Yes, you can modify state of objects inside your stream, but most often 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));
// ^ ^^^^^^^^^^^^^
// \__/
但这在大多数情况下不是
but this in most cases is not
users.stream().forEach(u -> users.remove(u));
//^^^^^ ^^^^^^^^^^^^
// \_____________________/
并可能抛出 ConcurrentModificationException
甚至其他意外异常,例如 NPE:
and may throw ConcurrentModificationException
or even other unexpected 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中修改流中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代时在Java8中修改流中的对象
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01