Remove Element from Set

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 filter and collect. The filter method simply filters out the elements from the stream that should be carried on to the next step. The collect method combines elements to a Collection of some sort or 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 Set containing the String objects of odd length.

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


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

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

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

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