Remove multiple keys from Map in efficient way?

前端 未结 4 1555
攒了一身酷
攒了一身酷 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:18

    For the sake of completion, and since Google brings you here when you look for a way to achieve this:

    map.entrySet().removeIf(entry -> /* decide what you want to remove here */ );
    

    This does not assume you have a predefined set of keys to remove but rather assumes you have a condition on which the keys should be removed. From the question, it is unclear if these keys are added manually or based on some sort of condition. In the latter case, this might be the cleaner code.

    For the former case, this (untested) code might work as well:

    map.entrySet().removeIf(entry -> keySet.contains(entry.getKey()) );
    

    But obviously the answer provided by @assylias is much cleaner in this case!

提交回复
热议问题