Remove multiple keys from Map in efficient way?

前端 未结 4 1543
攒了一身酷
攒了一身酷 2020-12-02 17:58

I have a Map with large number of key values pairs. Now I want to remove selected keys from that Map. Following code shows wha

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 18:20

    Just for the sake of completeness:

    As guessed java.util.AbstractSet#removeAll really iterates over all entries, but with one little trick: It uses the iterator of the smaller collection:

    if (size() <= collection.size()) {
        Iterator it = iterator();
        while (it.hasNext()) {
            if (collection.contains(it.next())) {
                it.remove();
            }
        }
    } else {
        Iterator it = collection.iterator();
        while (it.hasNext()) {
            remove(it.next());
        }
    }
    

提交回复
热议问题