What's the quickest way to remove an element from a Map by value in Java?

后端 未结 12 562
臣服心动
臣服心动 2020-12-09 01:36

What\'s the quickest way to remove an element from a Map by value in Java?

Currently I\'m using:

    DomainObj valueToRemove = new DomainObj();
    S         


        
12条回答
  •  Happy的楠姐
    2020-12-09 01:54

    Like most of the other posters have said, it's generally an O(N) operation because you're going to have to look through the whole list of hashtable values regardless. @tackline has the right solution for keeping the memory usage at O(1) (I gave him an up-vote for that).

    Your other option is to sacrifice memory space for the sake of speed. If your map is reasonably sized, you could store two maps in parallel.

    If you have a Map then maintain a Map in parallel to it. When you insert/remove on one map, do it on the other also. Granted this is uglier because you're wasting space and you'll have to make sure the "hashCode" method of DomainObj is written properly, but your removal time drops from O(N) to O(1) because you can lookup the key/object mapping in constant time either direction.

    Not generally the best solution, but if your number one concern is speed, I think this is probably as fast as you're gonna get.

    ==================== Addendum: This essentially what @msaeed suggested just sans the third party library.

提交回复
热议问题