gpt4 book ai didi

java - 在 Java8 Stream 上调用 Filter 方法

转载 作者:行者123 更新时间:2023-11-29 07:28:42 24 4
gpt4 key购买 nike

是否可以更新Stream数据直接返回?我想根据消费者发送的请求参数更新流数据,请参阅下面的代码。

Supplier<Stream<User>> userStream = users::stream;

userStream.get().filter(user -> user.getRole().getType().getName().equalsIgnoreCase(value));
userStream.get().filter(user -> user.getDownloadCertificate() == check );

最佳答案

您无法更新 Stream,因为它不是数据结构,而是支持顺序和并行聚合操作的元素序列(来源:https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html)。

Java 8 文档解释了流和集合之间的主要区别:

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. However, if the provided stream operations do not offer the desired functionality, the BaseStream.iterator() and BaseStream.spliterator() operations can be used to perform a controlled traversal.

A stream pipeline, like the "widgets" example above, can be viewed as a query on the stream source. Unless the source was explicitly designed for concurrent modification (such as a ConcurrentHashMap), unpredictable or erroneous behavior may result from modifying the stream source while it is being queried.

Source: https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html

在您的案例中,流的理想用法可能如下所示:

List<User> users = getUsers(); // let's assume this method returns a list of users
String name = "some name";
boolean check = true;

//Now let's create a new list of filtered users
List<User> filteredUsers = users.stream()
.filter(user -> user.getRole().getType().getName().equalsIgnoreCase(name))
.filter(user -> user.getDownloadCertificate() == check)
.collect(Collectors.toList());

请记住,初始用户列表未被修改。调用终端操作(.collect)时 Stream 迭代一次。

关于java - 在 Java8 Stream 上调用 Filter 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46329870/

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