Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Element from Set

Tags:

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);
        }
    }
}
like image 688
f3d0r Avatar asked Jan 27 '15 19:01

f3d0r


People also ask

How do you remove an element from a set?

Python Set remove() MethodThe remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.

How do you add and remove an element from a set in Python?

The built-in method, discard() in Python, removes the element from the set only if the element is present in the set. If the element is not present in the set, then no error or exception is raised and the original set is printed.

How do I remove an element from a set in CPP?

Deleting a single element from the set container is very simple in C++. The idea is to pass the given element to the set::erase function, which erases it from the set.

How do I remove multiple elements from a set?

Given a set, the task is to write a Python program remove multiple elements from set. Example: Input : test_set = {6, 4, 2, 7, 9}, rem_ele = [2, 4, 8] Output : {9, 6, 7} Explanation : 2, 4 are removed from set.


1 Answers

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

like image 180
M A Avatar answered Oct 09 '22 07:10

M A