Search code examples
javastringforeachsetstring-length

Remove Element from Set


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);
        }
    }
}

Solution

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