I have a list of around 100,000 employees in Java. Now I want to delete a particular employee object from list quickly. What are the possible ways to do it without iterating the whole list? (If I iterate each object, compare the details then delete: this scenario takes lot of time)
You need a means of find the object quickly. You could
O(log N)
Note: actually removing an element from an ArrayList is O(n)
While LinkedList as O(1)
for remove, a binary search on it would be pointless i.e. much slower than O(N)
O(1)
amortised. You could use a LinkedHashSet
if you would like to preserve some order such as order of insertion.enabled
which you set to false
instead of actually removing it. You could remove it later as a batch job at some time (overnight or on the weekend)Now I want to delete a particular employee object from list ...
You can just use List.remove to do this
... quickly
In practice, even though removing the item might be an O(1)
operation, iterating over the full length of the list is O(n)
, and is, as you susepcted, not very fast.
I feel that your problem would better be served by the power of a hashmap. This has constant lookup and removal time. The LinkedHashMap class might suit your needs. It maintains insertion order the same way a linked list does, but it also has constant time insertion and deletion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With