Remove Element from Set

f3d0r picture f3d0r · Jan 27, 2015 · Viewed 43.4k times · Source

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.

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

Answer

M A picture M A · Jan 27, 2015

A Set has no concept of an index of an element. The elements have no order in the set. Moreover, you should use an Iterator when iterating to avoid a ConcurrentModificationException when removing an element from a collection while looping over it:

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().