Remove item from set

I am trying to delete all lines having an even length in a set. Here is my code so far, but it's hard for me to get the index from the iterator in extended for loop.

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

A Setdoes not have the concept of an element index. Elements have no order in the set. In addition, you should use Iteratoriterating to avoid ConcurrentModificationExceptionwhen deleting an item from the collection when going through it:

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

Pay attention to the call Iterator.remove()instead Set.remove().

+19
source

, Java 8, - . Java 8 Streams , filter collect. filter , . collect Collection 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

, Set String .

Java 8, Oracle JavaDocs.

+5

. 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();
    }
}
+3

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

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

All Articles