Java – delete element from set

I'm trying to delete all strings of uniform length in a group So far, this is my code, but I can't get the index from the iterator in the enhanced for loop

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

Solution

Collection has no concept of element index Elements have no order in the collection In addition, iterators should be used during iterations to avoid using concurrentmodificationexception when removing elements from the collection during a loop:

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

Please note that for iterator Remove() instead of set Call to remove()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>