Can Java 8 Streams operate on an item in a collection, and then remove it?(Java 8 Streams 可以对集合中的项目进行操作,然后将其删除吗?)
问题描述
和几乎所有人一样,我仍在学习新的 Java 8 Streams API 的复杂性(并喜欢它们).我有一个关于流使用的问题.我将提供一个简化的示例.
Like just about everyone, I'm still learning the intricacies (and loving them) of the new Java 8 Streams API. I have a question concerning usage of streams. I'll provide a simplified example.
Java Streams 允许我们获取一个 Collection
,并在其上使用 stream()
方法来接收其所有元素的流.其中有许多有用的方法,例如 filter()
、map()
和 forEach()
,它们允许我们对内容使用 lambda 操作.
Java Streams allows us to take a Collection
, and use the stream()
method on it to receive a stream of all of its elements. Within it, there are a number of useful methods, such as filter()
, map()
, and forEach()
, which allow us to use lambda operations on the contents.
我的代码看起来像这样(简化):
I have code that looks something like this (simplified):
set.stream().filter(item -> item.qualify())
.map(item -> (Qualifier)item).forEach(item -> item.operate());
set.removeIf(item -> item.qualify());
这个想法是获取集合中所有匹配某个限定符的项目的映射,然后通过它们进行操作.手术后,它们不再有任何用途,应从原始集合中删除.代码运行良好,但我无法摆脱 Stream
中有一个操作可以在一行中为我执行此操作的感觉.
The idea is to get a mapping of all items in the set, which match a certain qualifier, and then operate through them. After the operation, they serve no further purpose, and should be removed from the original set. The code works well, but I can't shake the feeling that there's an operation in Stream
that could do this for me, in a single line.
如果它在 Javadocs 中,我可能会忽略它.
If it's in the Javadocs, I may be overlooking it.
有没有更熟悉 API 的人看到类似的东西?
Does anyone more familiar with the API see something like that?
推荐答案
你可以这样做:
set.removeIf(item -> {
if (!item.qualify())
return false;
item.operate();
return true;
});
如果 item.operate()
总是返回 true
你可以非常简洁地做到这一点.
If item.operate()
always returns true
you can do it very succinctly.
set.removeIf(item -> item.qualify() && item.operate());
但是,我不喜欢这些方法,因为目前尚不清楚发生了什么.就个人而言,我会继续为此使用 for
循环和 Iterator
.
However, I don't like these approaches as it is not immediately clear what is going on. Personally, I would continue to use a for
loop and an Iterator
for this.
for (Iterator<Item> i = set.iterator(); i.hasNext();) {
Item item = i.next();
if (item.qualify()) {
item.operate();
i.remove();
}
}
这篇关于Java 8 Streams 可以对集合中的项目进行操作,然后将其删除吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 Streams 可以对集合中的项目进行操作,然后将其删除吗?


基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01