Java 8 Streams是否可以对集合中的项目进行操作,然后将其删除? [英] Can Java 8 Streams operate on an item in a collection, and then remove it?
问题描述
像大家一样,我仍然在学习新的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
c $ c> 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看到这样? p>
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());
但是,我不喜欢这些方法,因为它不是立即清楚发生了什么。就我个人而言,我会继续使用来替换
循环和迭代器
。
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是否可以对集合中的项目进行操作,然后将其删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!