Java 8 Streams 可以对集合中的项目进行操作,然后将其删除吗?将其、以对、操作、项目

2023-09-07 01:48:59 作者:痴心℃留不住

和几乎所有人一样,我仍在学习新的 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();
    }
}