Java 从集合中删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28178554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:44:31  来源:igfitidea点击:

Remove Element from Set

javastringforeachsetstring-length

提问by f3d0r

I'm trying to remove all Strings that are of even length in a set. Here is my code so far, but I am having trouble getting the index from the iterator in the enhanced-for-loop.

我正在尝试删除一组中长度为偶数的所有字符串。到目前为止,这是我的代码,但我无法从增强型 for 循环中的迭代器获取索引。

public static void removeEvenLength(Set<String> list) {
    for (String s : list) {
        if (s.length() % 2 == 0) {
            list.remove(s);
        }
    }
}

采纳答案by M Anouti

A Sethas no concept of an index of an element. The elements have no order in the set. Moreover, you should use an Iteratorwhen iterating to avoid a ConcurrentModificationExceptionwhen removing an element from a collection whilelooping over it:

ASet没有元素索引的概念。元素在集合中没有顺序。此外,你应该使用Iterator时迭代,以避免ConcurrentModificationException从集合中移除元素时,同时遍历它:

for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String s =  iterator.next();
    if (s.length() % 2 == 0) {
        iterator.remove();
    }       
}

Note the call to Iterator.remove()instead of Set.remove().

请注意对Iterator.remove()而不是的调用Set.remove()

回答by rgettman

You don't need the index. But you do need the explicit Iterator. The iterator has the remove()method, no parameters, that removes the current item from the collection.

你不需要索引。但是您确实需要明确的Iterator. 迭代器具有从集合中删除当前项的remove()方法,没有参数。

Iterator<String> itr = list.iterator();  // list is a Set<String>!
while (itr.hasNext())
{
    String s = itr.next();
    if (s.length() % 2 == 0) {
        itr.remove();
    }
}

回答by wassgren

Just thought that I'd post a Java 8 solution that may help someone in the future. Java 8 Streams offers a bunch of nice methods such as filterand collect. The filtermethod simply filters out the elements from the stream that should be carried on to the next step. The collectmethod combines elements to a Collectionof some sort or a Map.

只是想我会发布一个 Java 8 解决方案,将来可能会对某人有所帮助。Java 8 Streams 提供了许多不错的方法,例如filtercollect。该filter方法只是从流中过滤掉应该继续进行下一步的元素。该collect方法将元素组合Collection为某种类型的 a 或 a Map

// The data to filter
final Set<String> strings = 
        new HashSet<>(Arrays.asList("a", "ab", "abc", "abcd"));

// Now, stream it!
final Set<String> odds =
        strings.stream()
               .filter(s -> s.length() % 2 != 0) // keep the odds
               .collect(Collectors.toSet());     // collect to a new set

This does not actually modify the original collection but creates a new Setcontaining the Stringobjects of odd length.

这实际上不会修改原始集合,而是创建一个Set包含String奇数长度对象的新集合。

For more reading on Java 8 Streams, checkout this excellent tutorial from Oracleor the great JavaDocs.

有关 Java 8 Streams 的更多阅读,请查看来自 Oracle 的优秀教程优秀的 JavaDocs

回答by Leonardo Lima

Java 8 has introduced Collection.removeIf(), which allows you to do:

Java 8 引入了Collection.removeIf(),它允许您执行以下操作:

set.removeIf(s -> s.length() % 2 == 0)