Remove item from HashMap, Java Question?

Hi, I want to remove an item from the HashMap by applying criteria. Consider this code:

    Set set = myMap.keySet();
    Iterator itr = set.iterator();
    while (itr.hasNext())
    {
        Object o = itr.next();
        if (o.toString().length() < 3) {
            myMap.remove(o.toString()); //remove the pair if key length is less then 3
    }

So, I get the ConcurentModification Exception runtime because during the iteration I modify the HashMap. What should I do? Are there any other ways to search my criteria and run the remove command at the end so that I can avoid this exception?

+3
source share
5 answers

Use itr.remove()insteadmyMap.remove(o.toString())

+12
source

As with Java 8, Collection provides removeIf(Predicate<? super E>)that will remove all elements for which the given predicate returns true. The example in the question can be rewritten as

myMap.keySet().removeIf(o -> o.toString().length() < 3);

, Collection, Iterator.remove, , . , removeIf .

+4

, Iterator.remove(). Iterator , . Map.remove(), , .. .

(, ..).

+3

- itr.remove()

, ( ). .

Iterator keySet() HashIterator, remove() HashMap.this.removeEntryForKey(key);

entrySet(), , - .

+1

, , :

Map<String,Object> map = // obtained somehow;

Map<String,Object> filtered = Maps.filterKeys(map, new Predicate() {
    @Override
    public boolean apply(String input) {
        return input.length() < 3;
    }
});

google. , , .

0

Source: https://habr.com/ru/post/1777353/


All Articles